agora inbox for [email protected]
help / color / mirror / Atom feed[PATCH v3 4/7] Row pattern recognition patch (executor).
201+ messages / 4 participants
[nested] [flat]
* [PATCH v3 4/7] Row pattern recognition patch (executor).
@ 2023-07-26 10:49 Tatsuo Ishii <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Tatsuo Ishii @ 2023-07-26 10:49 UTC (permalink / raw)
---
src/backend/executor/nodeWindowAgg.c | 701 ++++++++++++++++++++++++++-
src/backend/utils/adt/windowfuncs.c | 38 +-
src/include/catalog/pg_proc.dat | 6 +
src/include/nodes/execnodes.h | 18 +
src/include/windowapi.h | 8 +
5 files changed, 758 insertions(+), 13 deletions(-)
diff --git a/src/backend/executor/nodeWindowAgg.c b/src/backend/executor/nodeWindowAgg.c
index 310ac23e3a..0586bf57d6 100644
--- a/src/backend/executor/nodeWindowAgg.c
+++ b/src/backend/executor/nodeWindowAgg.c
@@ -36,6 +36,7 @@
#include "access/htup_details.h"
#include "catalog/objectaccess.h"
#include "catalog/pg_aggregate.h"
+#include "catalog/pg_collation_d.h"
#include "catalog/pg_proc.h"
#include "executor/executor.h"
#include "executor/nodeWindowAgg.h"
@@ -48,6 +49,7 @@
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/datum.h"
+#include "utils/fmgroids.h"
#include "utils/expandeddatum.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
@@ -159,6 +161,14 @@ typedef struct WindowStatePerAggData
bool restart; /* need to restart this agg in this cycle? */
} WindowStatePerAggData;
+/*
+ * Map between Var attno in a target list and the parsed attno.
+ */
+typedef struct AttnoMap {
+ List *attno; /* att number in target list (list of AttNumber) */
+ List *attnosyn; /* parsed att number (list of AttNumber) */
+} AttnoMap;
+
static void initialize_windowaggregate(WindowAggState *winstate,
WindowStatePerFunc perfuncstate,
WindowStatePerAgg peraggstate);
@@ -182,8 +192,9 @@ static void begin_partition(WindowAggState *winstate);
static void spool_tuples(WindowAggState *winstate, int64 pos);
static void release_partition(WindowAggState *winstate);
-static int row_is_in_frame(WindowAggState *winstate, int64 pos,
+static int row_is_in_frame(WindowAggState *winstate, int64 pos,
TupleTableSlot *slot);
+
static void update_frameheadpos(WindowAggState *winstate);
static void update_frametailpos(WindowAggState *winstate);
static void update_grouptailpos(WindowAggState *winstate);
@@ -195,9 +206,19 @@ static Datum GetAggInitVal(Datum textInitVal, Oid transtype);
static bool are_peers(WindowAggState *winstate, TupleTableSlot *slot1,
TupleTableSlot *slot2);
-static bool window_gettupleslot(WindowObject winobj, int64 pos,
- TupleTableSlot *slot);
+static void attno_map(Node *node, AttnoMap *map);
+static bool attno_map_walker(Node *node, void *context);
+static int row_is_in_reduced_frame(WindowObject winobj, int64 pos);
+
+static int64 evaluate_pattern(WindowObject winobj, int64 current_pos,
+ char *vname, StringInfo encoded_str, bool *result);
+
+static bool get_slots(WindowObject winobj, int64 current_pos);
+
+static int search_str_set(char *pattern, StringInfo *str_set, int set_size);
+static void search_str_set_recurse(char *pattern, StringInfo *str_set, int set_size, int set_index,
+ char *encoded_str, int *resultlen);
/*
* initialize_windowaggregate
@@ -673,6 +694,9 @@ eval_windowaggregates(WindowAggState *winstate)
WindowObject agg_winobj;
TupleTableSlot *agg_row_slot;
TupleTableSlot *temp_slot;
+ bool reduced_frame_set;
+ bool check_reduced_frame;
+ int num_rows_in_reduced_frame;
numaggs = winstate->numaggs;
if (numaggs == 0)
@@ -790,6 +814,7 @@ eval_windowaggregates(WindowAggState *winstate)
(winstate->frameOptions & FRAMEOPTION_EXCLUSION) ||
winstate->aggregatedupto <= winstate->frameheadpos)
{
+ elog(DEBUG1, "peraggstate->restart is set");
peraggstate->restart = true;
numaggs_restart++;
}
@@ -861,8 +886,10 @@ eval_windowaggregates(WindowAggState *winstate)
* If we created a mark pointer for aggregates, keep it pushed up to frame
* head, so that tuplestore can discard unnecessary rows.
*/
+#ifdef NOT_USED
if (agg_winobj->markptr >= 0)
WinSetMarkPosition(agg_winobj, winstate->frameheadpos);
+#endif
/*
* Now restart the aggregates that require it.
@@ -919,6 +946,10 @@ eval_windowaggregates(WindowAggState *winstate)
ExecClearTuple(agg_row_slot);
}
+ reduced_frame_set = false;
+ check_reduced_frame = false;
+ num_rows_in_reduced_frame = 0;
+
/*
* Advance until we reach a row not in frame (or end of partition).
*
@@ -930,12 +961,18 @@ eval_windowaggregates(WindowAggState *winstate)
{
int ret;
+ elog(DEBUG1, "===== loop in frame starts: " INT64_FORMAT, winstate->aggregatedupto);
+
/* Fetch next row if we didn't already */
if (TupIsNull(agg_row_slot))
{
if (!window_gettupleslot(agg_winobj, winstate->aggregatedupto,
agg_row_slot))
+ {
+ if (check_reduced_frame)
+ winstate->aggregatedupto--;
break; /* must be end of partition */
+ }
}
/*
@@ -944,10 +981,47 @@ eval_windowaggregates(WindowAggState *winstate)
*/
ret = row_is_in_frame(winstate, winstate->aggregatedupto, agg_row_slot);
if (ret < 0)
+ {
+ if (winstate->patternVariableList != NIL && check_reduced_frame)
+ winstate->aggregatedupto--;
break;
+ }
if (ret == 0)
goto next_tuple;
+ if (winstate->patternVariableList != NIL)
+ {
+ if (!reduced_frame_set)
+ {
+ num_rows_in_reduced_frame = row_is_in_reduced_frame(winstate->agg_winobj, winstate->aggregatedupto);
+ reduced_frame_set = true;
+ elog(DEBUG1, "set num_rows_in_reduced_frame: %d pos: " INT64_FORMAT,
+ num_rows_in_reduced_frame, winstate->aggregatedupto);
+
+ if (num_rows_in_reduced_frame <= 0)
+ break;
+
+ else if (num_rows_in_reduced_frame > 0)
+ check_reduced_frame = true;
+ }
+
+ if (check_reduced_frame)
+ {
+ elog(DEBUG1, "decrease num_rows_in_reduced_frame: %d pos: " INT64_FORMAT,
+ num_rows_in_reduced_frame, winstate->aggregatedupto);
+ num_rows_in_reduced_frame--;
+ if (num_rows_in_reduced_frame < 0)
+ {
+ /*
+ * No more rows remain in the reduced frame. Finish
+ * accumulating row into the aggregates.
+ */
+ winstate->aggregatedupto--;
+ break;
+ }
+ }
+ }
+
/* Set tuple context for evaluation of aggregate arguments */
winstate->tmpcontext->ecxt_outertuple = agg_row_slot;
@@ -976,6 +1050,8 @@ next_tuple:
ExecClearTuple(agg_row_slot);
}
+ elog(DEBUG1, "===== break loop in frame starts: " INT64_FORMAT, winstate->aggregatedupto);
+
/* The frame's end is not supposed to move backwards, ever */
Assert(aggregatedupto_nonrestarted <= winstate->aggregatedupto);
@@ -2053,6 +2129,8 @@ ExecWindowAgg(PlanState *pstate)
CHECK_FOR_INTERRUPTS();
+ elog(DEBUG1, "ExecWindowAgg called. pos: " INT64_FORMAT , winstate->currentpos);
+
if (winstate->status == WINDOWAGG_DONE)
return NULL;
@@ -2388,6 +2466,12 @@ ExecInitWindowAgg(WindowAgg *node, EState *estate, int eflags)
TupleDesc scanDesc;
ListCell *l;
+ TargetEntry *te;
+ Expr *expr;
+ Var *var;
+ int nargs;
+ AttnoMap attnomap;
+
/* check for unsupported flags */
Assert(!(eflags & (EXEC_FLAG_BACKWARD | EXEC_FLAG_MARK)));
@@ -2483,6 +2567,16 @@ ExecInitWindowAgg(WindowAgg *node, EState *estate, int eflags)
winstate->temp_slot_2 = ExecInitExtraTupleSlot(estate, scanDesc,
&TTSOpsMinimalTuple);
+ winstate->prev_slot = ExecInitExtraTupleSlot(estate, scanDesc,
+ &TTSOpsMinimalTuple);
+
+ winstate->next_slot = ExecInitExtraTupleSlot(estate, scanDesc,
+ &TTSOpsMinimalTuple);
+
+ winstate->null_slot = ExecInitExtraTupleSlot(estate, scanDesc,
+ &TTSOpsMinimalTuple);
+ winstate->null_slot = ExecStoreAllNullTuple(winstate->null_slot);
+
/*
* create frame head and tail slots only if needed (must create slots in
* exactly the same cases that update_frameheadpos and update_frametailpos
@@ -2667,6 +2761,69 @@ ExecInitWindowAgg(WindowAgg *node, EState *estate, int eflags)
winstate->inRangeAsc = node->inRangeAsc;
winstate->inRangeNullsFirst = node->inRangeNullsFirst;
+ /* Set up SKIP TO type */
+ winstate->rpSkipTo = node->rpSkipTo;
+ /* Set up row pattern recognition PATTERN clause */
+ winstate->patternVariableList = node->patternVariable;
+ winstate->patternRegexpList = node->patternRegexp;
+
+ /* Set up row pattern recognition DEFINE clause */
+
+ /*
+ * Collect mapping between varattno and varattnosyn in the targetlist.
+ * XXX: For now we only check RPR's argument. Eventually we have to
+ * recurse the targetlist to find out all mappings in Var nodes.
+ */
+ attnomap.attno = NIL;
+ attnomap.attnosyn = NIL;
+
+ foreach (l, node->plan.targetlist)
+ {
+ te = lfirst(l);
+ if (IsA(te->expr, WindowFunc))
+ {
+ WindowFunc *func = (WindowFunc *)te->expr;
+
+ /* sanity check */
+ nargs = list_length(func->args);
+ if (nargs != 1)
+ continue;
+
+ expr = (Expr *) lfirst(list_head(func->args));
+ if (!IsA(expr, Var))
+ continue;
+
+ var = (Var *)expr;
+ elog(DEBUG1, "resname: %s varattno: %d varattnosyn: %d",
+ te->resname, var->varattno, var->varattnosyn);
+ attnomap.attno = lappend_int(attnomap.attno, var->varattno);
+ attnomap.attnosyn = lappend_int(attnomap.attnosyn, var->varattnosyn);
+ }
+ }
+
+ winstate->defineVariableList = NIL;
+ winstate->defineClauseList = NIL;
+ if (node->defineClause != NIL)
+ {
+ foreach(l, node->defineClause)
+ {
+ char *name;
+ ExprState *exps;
+
+ te = lfirst(l);
+ name = te->resname;
+ expr = te->expr;
+
+ elog(DEBUG1, "defineVariable name: %s", name);
+ winstate->defineVariableList = lappend(winstate->defineVariableList,
+ makeString(pstrdup(name)));
+ /* tweak expr so that it referes to outer slot */
+ attno_map((Node *)expr, &attnomap);
+ exps = ExecInitExpr(expr, (PlanState *) winstate);
+ winstate->defineClauseList = lappend(winstate->defineClauseList, exps);
+ }
+ }
+
winstate->all_first = true;
winstate->partition_spooled = false;
winstate->more_partitions = false;
@@ -2674,6 +2831,77 @@ ExecInitWindowAgg(WindowAgg *node, EState *estate, int eflags)
return winstate;
}
+/*
+ * Rewrite Var node's varattno to the varattno which is used in the target
+ * list using AttnoMap. We also rewrite varno so that it sees outer tuple
+ * (PREV) or inner tuple (NEXT).
+ */
+static void
+attno_map(Node *node, AttnoMap *map)
+{
+ (void) expression_tree_walker(node, attno_map_walker, (void *) map);
+}
+
+static bool
+attno_map_walker(Node *node, void *context)
+{
+ FuncExpr *func;
+ int nargs;
+ Expr *expr;
+ Var *var;
+ AttnoMap *attnomap;
+ ListCell *lc1, *lc2;
+
+ if (node == NULL)
+ return false;
+
+ attnomap = (AttnoMap *) context;
+
+ if (IsA(node, FuncExpr))
+ {
+ func = (FuncExpr *)node;
+
+ if (func->funcid == F_PREV || func->funcid == F_NEXT)
+ {
+ /* sanity check */
+ nargs = list_length(func->args);
+ if (list_length(func->args) != 1)
+ elog(ERROR, "PREV/NEXT must have 1 argument but function %d has %d args", func->funcid, nargs);
+
+ expr = (Expr *) lfirst(list_head(func->args));
+ if (!IsA(expr, Var))
+ elog(ERROR, "PREV/NEXT's arg is not Var"); /* XXX: is it possible that arg type is Const? */
+ var = (Var *)expr;
+
+ if (func->funcid == F_PREV)
+ var->varno = OUTER_VAR;
+ else
+ var->varno = INNER_VAR;
+ }
+ return expression_tree_walker(node, attno_map_walker, (void *) context);
+ }
+ else if (IsA(node, Var))
+ {
+ var = (Var *)node;
+
+ elog(DEBUG1, "original varno: %d varattno: %d", var->varno, var->varattno);
+
+ forboth(lc1, attnomap->attno, lc2, attnomap->attnosyn)
+ {
+ int attno = lfirst_int(lc1);
+ int attnosyn = lfirst_int(lc2);
+
+ elog(DEBUG1, "walker: varattno: %d varattnosyn: %d",attno, attnosyn);
+ if (var->varattno == attnosyn)
+ {
+ elog(DEBUG1, "loc: %d rewrite varattno from: %d to %d", var->location, attnosyn, attno);
+ var->varattno = attno;
+ }
+ }
+ }
+ return expression_tree_walker(node, attno_map_walker, (void *) context);
+}
+
/* -----------------
* ExecEndWindowAgg
* -----------------
@@ -2691,6 +2919,8 @@ ExecEndWindowAgg(WindowAggState *node)
ExecClearTuple(node->agg_row_slot);
ExecClearTuple(node->temp_slot_1);
ExecClearTuple(node->temp_slot_2);
+ ExecClearTuple(node->prev_slot);
+ ExecClearTuple(node->next_slot);
if (node->framehead_slot)
ExecClearTuple(node->framehead_slot);
if (node->frametail_slot)
@@ -2740,6 +2970,8 @@ ExecReScanWindowAgg(WindowAggState *node)
ExecClearTuple(node->agg_row_slot);
ExecClearTuple(node->temp_slot_1);
ExecClearTuple(node->temp_slot_2);
+ ExecClearTuple(node->prev_slot);
+ ExecClearTuple(node->next_slot);
if (node->framehead_slot)
ExecClearTuple(node->framehead_slot);
if (node->frametail_slot)
@@ -3080,7 +3312,7 @@ are_peers(WindowAggState *winstate, TupleTableSlot *slot1,
*
* Returns true if successful, false if no such row
*/
-static bool
+bool
window_gettupleslot(WindowObject winobj, int64 pos, TupleTableSlot *slot)
{
WindowAggState *winstate = winobj->winstate;
@@ -3100,7 +3332,7 @@ window_gettupleslot(WindowObject winobj, int64 pos, TupleTableSlot *slot)
return false;
if (pos < winobj->markpos)
- elog(ERROR, "cannot fetch row before WindowObject's mark position");
+ elog(ERROR, "cannot fetch row: " INT64_FORMAT " before WindowObject's mark position: " INT64_FORMAT, pos, winobj->markpos );
oldcontext = MemoryContextSwitchTo(winstate->ss.ps.ps_ExprContext->ecxt_per_query_memory);
@@ -3420,14 +3652,54 @@ WinGetFuncArgInFrame(WindowObject winobj, int argno,
WindowAggState *winstate;
ExprContext *econtext;
TupleTableSlot *slot;
- int64 abs_pos;
- int64 mark_pos;
Assert(WindowObjectIsValid(winobj));
winstate = winobj->winstate;
econtext = winstate->ss.ps.ps_ExprContext;
slot = winstate->temp_slot_1;
+ if (WinGetSlotInFrame(winobj, slot,
+ relpos, seektype, set_mark,
+ isnull, isout) == 0)
+ {
+ econtext->ecxt_outertuple = slot;
+ return ExecEvalExpr((ExprState *) list_nth(winobj->argstates, argno),
+ econtext, isnull);
+ }
+
+ if (isout)
+ *isout = true;
+ *isnull = true;
+ return (Datum) 0;
+}
+
+/*
+ * WinGetSlotInFrame
+ * slot: TupleTableSlot to store the result
+ * relpos: signed rowcount offset from the seek position
+ * seektype: WINDOW_SEEK_HEAD or WINDOW_SEEK_TAIL
+ * set_mark: If the row is found/in frame and set_mark is true, the mark is
+ * moved to the row as a side-effect.
+ * isnull: output argument, receives isnull status of result
+ * isout: output argument, set to indicate whether target row position
+ * is out of frame (can pass NULL if caller doesn't care about this)
+ *
+ * Returns 0 if we successfullt got the slot. false if out of frame.
+ * (also isout is set)
+ */
+int
+WinGetSlotInFrame(WindowObject winobj, TupleTableSlot *slot,
+ int relpos, int seektype, bool set_mark,
+ bool *isnull, bool *isout)
+{
+ WindowAggState *winstate;
+ int64 abs_pos;
+ int64 mark_pos;
+ int num_reduced_frame;
+
+ Assert(WindowObjectIsValid(winobj));
+ winstate = winobj->winstate;
+
switch (seektype)
{
case WINDOW_SEEK_CURRENT:
@@ -3494,6 +3766,12 @@ WinGetFuncArgInFrame(WindowObject winobj, int argno,
winstate->frameOptions);
break;
}
+ num_reduced_frame = row_is_in_reduced_frame(winobj, winstate->frameheadpos);
+ if (num_reduced_frame < 0)
+ goto out_of_frame;
+ else if (num_reduced_frame > 0)
+ if (relpos >= num_reduced_frame)
+ goto out_of_frame;
break;
case WINDOW_SEEK_TAIL:
/* rejecting relpos > 0 is easy and simplifies code below */
@@ -3565,6 +3843,12 @@ WinGetFuncArgInFrame(WindowObject winobj, int argno,
mark_pos = 0; /* keep compiler quiet */
break;
}
+
+ num_reduced_frame = row_is_in_reduced_frame(winobj, winstate->frameheadpos + relpos);
+ if (num_reduced_frame < 0)
+ goto out_of_frame;
+ else if (num_reduced_frame > 0)
+ abs_pos = winstate->frameheadpos + relpos + num_reduced_frame - 1;
break;
default:
elog(ERROR, "unrecognized window seek type: %d", seektype);
@@ -3583,15 +3867,13 @@ WinGetFuncArgInFrame(WindowObject winobj, int argno,
*isout = false;
if (set_mark)
WinSetMarkPosition(winobj, mark_pos);
- econtext->ecxt_outertuple = slot;
- return ExecEvalExpr((ExprState *) list_nth(winobj->argstates, argno),
- econtext, isnull);
+ return 0;
out_of_frame:
if (isout)
*isout = true;
*isnull = true;
- return (Datum) 0;
+ return -1;
}
/*
@@ -3622,3 +3904,400 @@ WinGetFuncArgCurrent(WindowObject winobj, int argno, bool *isnull)
return ExecEvalExpr((ExprState *) list_nth(winobj->argstates, argno),
econtext, isnull);
}
+
+WindowAggState *
+WinGetAggState(WindowObject winobj)
+{
+ return winobj->winstate;
+}
+
+/*
+ * row_is_in_reduced_frame
+ * Determine whether a row is in the current row's reduced window frame according
+ * to row pattern matching
+ *
+ * The row must has been already determined that it is in a full window frame
+ * and fetched it into slot.
+ *
+ * Returns:
+ * = 0, RPR is not defined.
+ * >0, if the row is the first in the reduced frame. Return the number of rows in the reduced frame.
+ * -1, if the row is unmatched row
+ * -2, if the row is in the reduced frame but needed to be skipped because of
+ * AFTER MATCH SKIP PAST LAST ROW
+ */
+static
+int row_is_in_reduced_frame(WindowObject winobj, int64 pos)
+{
+ WindowAggState *winstate = winobj->winstate;
+ ListCell *lc1, *lc2;
+ bool expression_result;
+ int num_matched_rows;
+ int64 original_pos;
+ bool anymatch;
+ StringInfo encoded_str;
+ StringInfo pattern_str = makeStringInfo();
+
+ /*
+ * Array of pattern variables evaluted to true.
+ * Each character corresponds to pattern variable.
+ * Example:
+ * str_set[0] = "AB";
+ * str_set[1] = "AC";
+ * In this case at row 0 A and B are true, and A and C are true in row 1.
+ */
+ #define ENCODED_STR_ARRAY_ALLOC_SIZE 128
+ StringInfo *str_set = NULL;
+ int str_set_index;
+ int str_set_size;
+
+ if (winstate->patternVariableList == NIL)
+ {
+ /*
+ * RPR is not defined. Assume that we are always in the the reduced
+ * window frame.
+ */
+ return 0;
+ }
+
+ /* save original pos */
+ original_pos = pos;
+
+ /*
+ * Check whether the row speicied by pos is in the reduced frame. The
+ * second and subsequent rows need to be recognized as "unmatched" rows if
+ * AFTER MATCH SKIP PAST LAST ROW is defined.
+ */
+ if (winstate->rpSkipTo == ST_PAST_LAST_ROW &&
+ pos > winstate->headpos_in_reduced_frame &&
+ pos < (winstate->headpos_in_reduced_frame + winstate->num_rows_in_reduced_frame))
+ return -2;
+
+ /*
+ * Loop over until none of pattern matches or encounters end of frame.
+ */
+ for (;;)
+ {
+ int64 result_pos = -1;
+
+ /*
+ * Loop over each PATTERN variable.
+ */
+ anymatch = false;
+ encoded_str = makeStringInfo();
+
+ forboth(lc1, winstate->patternVariableList, lc2, winstate->patternRegexpList)
+ {
+ char *vname = strVal(lfirst(lc1));
+ char *quantifier = strVal(lfirst(lc2));
+
+ elog(DEBUG1, "pos: " INT64_FORMAT " pattern vname: %s quantifier: %s", pos, vname, quantifier);
+
+ expression_result = false;
+
+ /* evaluate row pattern against current row */
+ result_pos = evaluate_pattern(winobj, pos, vname, encoded_str, &expression_result);
+ if (expression_result)
+ {
+ elog(DEBUG1, "expression result is true");
+ anymatch = true;
+ }
+
+ /*
+ * If out of frame, we are done.
+ */
+ if (result_pos < 0)
+ break;
+ }
+
+ if (!anymatch)
+ {
+ /* none of patterns matched. */
+ break;
+ }
+
+ /* build encoded string array */
+ if (str_set == NULL)
+ {
+ str_set_index = 0;
+ str_set_size = ENCODED_STR_ARRAY_ALLOC_SIZE * sizeof(StringInfo);
+ str_set = palloc(str_set_size);
+ }
+
+ str_set[str_set_index++] = encoded_str;
+
+ elog(DEBUG1, "pos: " INT64_FORMAT " str_set_index: %d encoded_str: %s", pos, str_set_index, encoded_str->data);
+
+ if (str_set_index >= str_set_size)
+ {
+ str_set_size *= 2;
+ str_set = repalloc(str_set, str_set_size);
+ }
+
+ /* move to next row */
+ pos++;
+
+ if (result_pos < 0)
+ {
+ /* out of frame */
+ break;
+ }
+ }
+
+ if (str_set == NULL)
+ {
+ /* no matches found in the first row */
+ return -1;
+ }
+
+ elog(DEBUG1, "pos: " INT64_FORMAT " encoded_str: %s", pos, encoded_str->data);
+
+ /* build regular expression */
+ pattern_str = makeStringInfo();
+ appendStringInfoChar(pattern_str, '^');
+ forboth(lc1, winstate->patternVariableList, lc2, winstate->patternRegexpList)
+ {
+ char *vname = strVal(lfirst(lc1));
+ char *quantifier = strVal(lfirst(lc2));
+
+ appendStringInfoChar(pattern_str, vname[0]);
+ if (quantifier[0])
+ appendStringInfoChar(pattern_str, quantifier[0]);
+ elog(DEBUG1, "vname: %s quantifier: %s", vname, quantifier);
+ }
+
+ elog(DEBUG1, "pos: " INT64_FORMAT " pattern: %s", pos, pattern_str->data);
+
+ /* look for matching pattern variable sequence */
+ num_matched_rows = search_str_set(pattern_str->data, str_set, str_set_index);
+ if (num_matched_rows <= 0)
+ return -1;
+
+ /*
+ * We are at the first row in the reduced frame. Save the number of
+ * matched rows as the number of rows in the reduced frame.
+ */
+ winstate->headpos_in_reduced_frame = original_pos;
+ winstate->num_rows_in_reduced_frame = num_matched_rows;
+
+ return num_matched_rows;
+}
+
+/*
+ * search set of encode_str.
+ * set_size: size of set_str array.
+ */
+static
+int search_str_set(char *pattern, StringInfo *str_set, int set_size)
+{
+ char *encoded_str = palloc0(set_size+1);
+ int resultlen = 0;
+
+ search_str_set_recurse(pattern, str_set, set_size, 0, encoded_str, &resultlen);
+ elog(DEBUG1, "search_str_set returns %d", resultlen);
+ return resultlen;
+}
+
+static
+void search_str_set_recurse(char *pattern, StringInfo *str_set, int set_size, int set_index, char *encoded_str, int *resultlen)
+{
+ char *p;
+
+ if (set_index >= set_size)
+ {
+ Datum d;
+ text *res;
+ char *substr;
+
+ /*
+ * We first perform pattern matching using regexp_instr, then call
+ * textregexsubstr to get matched substring to know how log the
+ * matched string is. That is the number of rows in the reduced window
+ * frame. The reason why we can't call textregexsubstr is, it error
+ * out if pattern is not match.
+ */
+ if (DatumGetInt32(DirectFunctionCall2Coll(regexp_instr, DEFAULT_COLLATION_OID,
+ PointerGetDatum(cstring_to_text(encoded_str)),
+ PointerGetDatum(cstring_to_text(pattern)))) > 0)
+ {
+ d = DirectFunctionCall2Coll(textregexsubstr,
+ DEFAULT_COLLATION_OID,
+ PointerGetDatum(cstring_to_text(encoded_str)),
+ PointerGetDatum(cstring_to_text(pattern)));
+ if (d != 0)
+ {
+ int len;
+
+ res = DatumGetTextPP(d);
+ substr = text_to_cstring(res);
+ len = strlen(substr);
+ if (len > *resultlen)
+ /* remember the longest match */
+ *resultlen = len;
+ }
+ }
+ return;
+ }
+
+ p = str_set[set_index]->data;
+ while (*p)
+ {
+ encoded_str[set_index] = *p;
+ p++;
+ search_str_set_recurse(pattern, str_set, set_size, set_index + 1, encoded_str, resultlen);
+ }
+}
+
+
+/*
+ * Evaluate expression associated with PATTERN variable vname.
+ * relpos is relative row position in a frame (starting from 0).
+ * "quantifier" is the quatifier part of the PATTERN regular expression.
+ * Currently only '+' is allowed.
+ * result is out paramater representing the expression evaluation result
+ * is true of false.
+ * Return values are:
+ * >=0: the last match absolute row position
+ * other wise out of frame.
+ */
+static
+int64 evaluate_pattern(WindowObject winobj, int64 current_pos,
+ char *vname, StringInfo encoded_str, bool *result)
+{
+ WindowAggState *winstate = winobj->winstate;
+ ExprContext *econtext = winstate->ss.ps.ps_ExprContext;
+ ListCell *lc1, *lc2;
+ ExprState *pat;
+ Datum eval_result;
+ bool out_of_frame = false;
+ bool isnull;
+
+ forboth (lc1, winstate->defineVariableList, lc2, winstate->defineClauseList)
+ {
+ char *name = strVal(lfirst(lc1));
+
+ if (strcmp(vname, name))
+ continue;
+
+ /* set expression to evaluate */
+ pat = lfirst(lc2);
+
+ /* get current, previous and next tuples */
+ if (!get_slots(winobj, current_pos))
+ {
+ out_of_frame = true;
+ }
+ else
+ {
+ /* evaluate the expression */
+ eval_result = ExecEvalExpr(pat, econtext, &isnull);
+ if (isnull)
+ {
+ /* expression is NULL */
+ elog(DEBUG1, "expression for %s is NULL at row: " INT64_FORMAT, vname, current_pos);
+ *result = false;
+ }
+ else
+ {
+ if (!DatumGetBool(eval_result))
+ {
+ /* expression is false */
+ elog(DEBUG1, "expression for %s is false at row: " INT64_FORMAT, vname, current_pos);
+ *result = false;
+ }
+ else
+ {
+ /* expression is true */
+ elog(DEBUG1, "expression for %s is true at row: " INT64_FORMAT, vname, current_pos);
+ appendStringInfoChar(encoded_str, vname[0]);
+ *result = true;
+ }
+ }
+ break;
+ }
+
+ if (out_of_frame)
+ {
+ *result = false;
+ return -1;
+ }
+ }
+ return current_pos;
+}
+
+/*
+ * Get current, previous and next tuples.
+ * Returns false if current row is out of partition/full frame.
+ */
+static
+bool get_slots(WindowObject winobj, int64 current_pos)
+{
+ WindowAggState *winstate = winobj->winstate;
+ TupleTableSlot *slot;
+ int ret;
+ ExprContext *econtext;
+
+ econtext = winstate->ss.ps.ps_ExprContext;
+
+ /* set up current row tuple slot */
+ slot = winstate->temp_slot_1;
+ if (!window_gettupleslot(winobj, current_pos, slot))
+ {
+ elog(DEBUG1, "current row is out of partition at:" INT64_FORMAT, current_pos);
+ return false;
+
+ ret = row_is_in_frame(winstate, current_pos, slot);
+ if (ret <= 0)
+ {
+ elog(DEBUG1, "current row is out of frame at: " INT64_FORMAT, current_pos);
+ return false;
+ }
+ }
+ econtext->ecxt_scantuple = slot;
+
+ /* for PREV */
+ if (current_pos > 0)
+ {
+ slot = winstate->prev_slot;
+ if (!window_gettupleslot(winobj, current_pos - 1, slot))
+ {
+ elog(DEBUG1, "previous row is out of partition at: " INT64_FORMAT, current_pos - 1);
+ econtext->ecxt_outertuple = winstate->null_slot;
+ }
+ else
+ {
+ ret = row_is_in_frame(winstate, current_pos - 1, slot);
+ if (ret <= 0)
+ {
+ elog(DEBUG1, "previous row is out of frame at: " INT64_FORMAT, current_pos - 1);
+ econtext->ecxt_outertuple = winstate->null_slot;
+ }
+ else
+ {
+ econtext->ecxt_outertuple = slot;
+ }
+ }
+ }
+ else
+ econtext->ecxt_outertuple = winstate->null_slot;
+
+ /* for NEXT */
+ slot = winstate->next_slot;
+ if (!window_gettupleslot(winobj, current_pos + 1, slot))
+ {
+ elog(DEBUG1, "next row is out of partiton at: " INT64_FORMAT, current_pos + 1);
+ econtext->ecxt_innertuple = winstate->null_slot;
+ }
+ else
+ {
+ ret = row_is_in_frame(winstate, current_pos + 1, slot);
+ if (ret <= 0)
+ {
+ elog(DEBUG1, "next row is out of frame at: " INT64_FORMAT, current_pos + 1);
+ econtext->ecxt_innertuple = winstate->null_slot;
+ }
+ else
+ econtext->ecxt_innertuple = slot;
+ }
+ return true;
+}
diff --git a/src/backend/utils/adt/windowfuncs.c b/src/backend/utils/adt/windowfuncs.c
index b87a624fb2..e4cab36ec9 100644
--- a/src/backend/utils/adt/windowfuncs.c
+++ b/src/backend/utils/adt/windowfuncs.c
@@ -13,6 +13,9 @@
*/
#include "postgres.h"
+#include "catalog/pg_collation_d.h"
+#include "executor/executor.h"
+#include "nodes/execnodes.h"
#include "nodes/supportnodes.h"
#include "utils/builtins.h"
#include "windowapi.h"
@@ -36,11 +39,19 @@ typedef struct
int64 remainder; /* (total rows) % (bucket num) */
} ntile_context;
+/*
+ * rpr process information.
+ * Used for AFTER MATCH SKIP PAST LAST ROW
+ */
+typedef struct SkipContext
+{
+ int64 pos; /* last row absolute position */
+} SkipContext;
+
static bool rank_up(WindowObject winobj);
static Datum leadlag_common(FunctionCallInfo fcinfo,
bool forward, bool withoffset, bool withdefault);
-
/*
* utility routine for *_rank functions.
*/
@@ -673,7 +684,7 @@ window_last_value(PG_FUNCTION_ARGS)
bool isnull;
result = WinGetFuncArgInFrame(winobj, 0,
- 0, WINDOW_SEEK_TAIL, true,
+ 0, WINDOW_SEEK_TAIL, false,
&isnull, NULL);
if (isnull)
PG_RETURN_NULL();
@@ -713,3 +724,26 @@ window_nth_value(PG_FUNCTION_ARGS)
PG_RETURN_DATUM(result);
}
+
+/*
+ * prev
+ * Dummy function to invoke RPR's navigation operator "PREV".
+ * This is *not* a window function.
+ */
+Datum
+window_prev(PG_FUNCTION_ARGS)
+{
+ PG_RETURN_DATUM(PG_GETARG_DATUM(0));
+}
+
+/*
+ * next
+ * Dummy function to invoke RPR's navigation operation "NEXT".
+ * This is *not* a window function.
+ */
+Datum
+window_next(PG_FUNCTION_ARGS)
+{
+ PG_RETURN_DATUM(PG_GETARG_DATUM(0));
+}
+
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 6996073989..fa100b2665 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -10397,6 +10397,12 @@
{ oid => '3114', descr => 'fetch the Nth row value',
proname => 'nth_value', prokind => 'w', prorettype => 'anyelement',
proargtypes => 'anyelement int4', prosrc => 'window_nth_value' },
+{ oid => '6122', descr => 'previous value',
+ proname => 'prev', provolatile => 's', prorettype => 'anyelement',
+ proargtypes => 'anyelement', prosrc => 'window_prev' },
+{ oid => '6123', descr => 'next value',
+ proname => 'next', provolatile => 's', prorettype => 'anyelement',
+ proargtypes => 'anyelement', prosrc => 'window_next' },
# functions for range types
{ oid => '3832', descr => 'I/O',
diff --git a/src/include/nodes/execnodes.h b/src/include/nodes/execnodes.h
index cb714f4a19..4fd3bd1a93 100644
--- a/src/include/nodes/execnodes.h
+++ b/src/include/nodes/execnodes.h
@@ -2519,6 +2519,14 @@ typedef struct WindowAggState
int64 groupheadpos; /* current row's peer group head position */
int64 grouptailpos; /* " " " " tail position (group end+1) */
+ /* these fields are used in Row pattern recognition: */
+ RPSkipTo rpSkipTo; /* Row Pattern Skip To type */
+ List *patternVariableList; /* list of row pattern variables names (list of String) */
+ List *patternRegexpList; /* list of row pattern regular expressions ('+' or ''. list of String) */
+ List *defineVariableList; /* list of row pattern definition variables (list of String) */
+ List *defineClauseList; /* expression for row pattern definition
+ * search conditions ExprState list */
+
MemoryContext partcontext; /* context for partition-lifespan data */
MemoryContext aggcontext; /* shared context for aggregate working data */
MemoryContext curaggcontext; /* current aggregate's working data */
@@ -2555,6 +2563,16 @@ typedef struct WindowAggState
TupleTableSlot *agg_row_slot;
TupleTableSlot *temp_slot_1;
TupleTableSlot *temp_slot_2;
+
+ /* temporary slots for RPR */
+ TupleTableSlot *prev_slot; /* PREV row navigation operator */
+ TupleTableSlot *next_slot; /* NEXT row navigation operator */
+ TupleTableSlot *null_slot; /* all NULL slot */
+
+ /* head of the reduced window frame */
+ int64 headpos_in_reduced_frame;
+ /* number of rows in the reduced window frame */
+ int64 num_rows_in_reduced_frame;
} WindowAggState;
/* ----------------
diff --git a/src/include/windowapi.h b/src/include/windowapi.h
index b8c2c565d1..1e292648e9 100644
--- a/src/include/windowapi.h
+++ b/src/include/windowapi.h
@@ -58,7 +58,15 @@ extern Datum WinGetFuncArgInFrame(WindowObject winobj, int argno,
int relpos, int seektype, bool set_mark,
bool *isnull, bool *isout);
+extern int WinGetSlotInFrame(WindowObject winobj, TupleTableSlot *slot,
+ int relpos, int seektype, bool set_mark,
+ bool *isnull, bool *isout);
+
extern Datum WinGetFuncArgCurrent(WindowObject winobj, int argno,
bool *isnull);
+extern WindowAggState *WinGetAggState(WindowObject winobj);
+
+extern bool window_gettupleslot(WindowObject winobj, int64 pos, TupleTableSlot *slot);
+
#endif /* WINDOWAPI_H */
--
2.25.1
----Next_Part(Wed_Jul_26_21_21_34_2023_317)--
Content-Type: Text/X-Patch; charset=us-ascii
Content-Transfer-Encoding: 7bit
Content-Disposition: inline;
filename="v3-0005-Row-pattern-recognition-patch-docs.patch"
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* [PATCH v1] Add per-backend AIO statistics
@ 2026-06-11 09:45 Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-06-11 09:45 UTC (permalink / raw)
This commit adds per-backend AIO statistics, providing per-backend AIO behavior
details.
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns the following counters based on the PID
provided in input:
- started: total number of AIO operations initiated
- executed_sync: IOs that were executed synchronously (fallback path)
- executed_async: IOs that were submitted asynchronously to the IO method
- completed_self: IO completions processed by the issuing backend itself
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times the backend had to wait for a free AIO handle
- submitted: number of submitted calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion
patterns. That helps see how IO completion work is distributed and could
help interpret per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
This commit is straight-forward, relying on the infrastructure provided
by 9aea73fc61d4 (backend-level pgstats).
XXX: Bump catalog version. No need to touch PGSTAT_FILE_FORMAT_ID as backend
statistics are never written to disk.
Author: Bertrand Drouvot <[email protected]>
Reviewed-by:
Discussion:
---
doc/src/sgml/monitoring.sgml | 70 +++++++++++++
src/backend/storage/aio/aio.c | 13 +++
src/backend/utils/activity/pgstat_backend.c | 109 ++++++++++++++++++++
src/backend/utils/adt/pgstatfuncs.c | 60 +++++++++++
src/include/catalog/pg_proc.dat | 7 ++
src/include/pgstat.h | 25 +++++
src/include/utils/pgstat_internal.h | 3 +-
src/test/modules/test_aio/t/001_aio.pl | 32 ++++++
src/tools/pgindent/typedefs.list | 1 +
9 files changed, 319 insertions(+), 1 deletion(-)
24.4% doc/src/sgml/
3.2% src/backend/storage/aio/
25.3% src/backend/utils/activity/
20.5% src/backend/utils/adt/
4.9% src/include/catalog/
10.0% src/include/
11.1% src/test/modules/test_aio/t/
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 12b9ee20d4a..1c566cf0e0e 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -5641,6 +5641,76 @@ description | Waiting for a newly initialized WAL file to reach durable storage
</para></entry>
</row>
+ <row>
+ <entry id="pg-stat-get-backend-aio" role="func_table_entry"><para role="func_signature">
+ <indexterm>
+ <primary>pg_stat_get_backend_aio</primary>
+ </indexterm>
+ <function>pg_stat_get_backend_aio</function> ( <type>integer</type> )
+ <returnvalue>record</returnvalue>
+ </para>
+ <para>
+ Returns <acronym>AIO</acronym> (Asynchronous I/O) statistics about the
+ backend with the specified process ID. The returned values are:
+ <itemizedlist>
+ <listitem>
+ <para>
+ <literal>started</literal>: Total IOs initiated.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_sync</literal>: IOs executed synchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>executed_async</literal>: IOs submitted asynchronously.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_self</literal>: IO completions processed by this
+ backend.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>completed_other</literal>: IO completions processed on
+ behalf of other backends.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>handle_waits</literal>: Times waited for a free AIO handle.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>submitted</literal>: Number of submit calls to the IO
+ method. Compare with <literal>executed_async</literal> to determine
+ average batch size.
+ </para>
+ </listitem>
+ <listitem>
+ <para>
+ <literal>stats_reset</literal>: Timestamp of last stats reset.
+ </para>
+ </listitem>
+ </itemizedlist>
+ </para>
+ <para>
+ The <literal>completed_other</literal> column is only meaningful
+ when <varname>io_method</varname> is set to <literal>io_uring</literal>;
+ with <literal>worker</literal> mode, IO completions are processed by
+ IO worker processes which do not track these statistics.
+ </para>
+ <para>
+ The function does not return AIO statistics for the checkpointer,
+ the background writer, the startup process and the autovacuum launcher.
+ </para></entry>
+ </row>
+
<row>
<entry role="func_table_entry"><para role="func_signature">
<indexterm>
diff --git a/src/backend/storage/aio/aio.c b/src/backend/storage/aio/aio.c
index 8f7e26607b9..507f1727d41 100644
--- a/src/backend/storage/aio/aio.c
+++ b/src/backend/storage/aio/aio.c
@@ -40,6 +40,7 @@
#include "lib/ilist.h"
#include "miscadmin.h"
+#include "pgstat.h"
#include "port/atomics.h"
#include "storage/aio.h"
#include "storage/aio_internal.h"
@@ -458,6 +459,8 @@ pgaio_io_stage(PgAioHandle *ioh, PgAioOp op)
"staged (synchronous: %d, in_batch: %d)",
needs_synchronous, pgaio_my_backend->in_batchmode);
+ pgstat_count_backend_aio_start(needs_synchronous);
+
if (!needs_synchronous)
{
pgaio_my_backend->staged_ios[pgaio_my_backend->num_staged_ios++] = ioh;
@@ -544,6 +547,12 @@ pgaio_io_process_completion(PgAioHandle *ioh, int result)
/* condition variable broadcast ensures state is visible before wakeup */
ConditionVariableBroadcast(&ioh->cv);
+ /* Track AIO completion stats */
+ if (ioh->owner_procno == MyProcNumber)
+ pgstat_count_backend_aio_complete_self();
+ else
+ pgstat_count_backend_aio_complete_other();
+
/* contains call to pgaio_io_call_complete_local() */
if (ioh->owner_procno == MyProcNumber)
pgaio_io_reclaim(ioh);
@@ -762,6 +771,8 @@ pgaio_io_wait_for_free(void)
{
int reclaimed = 0;
+ pgstat_count_backend_aio_handle_wait();
+
pgaio_debug(DEBUG2, "waiting for free IO with %d pending, %u in-flight, %u idle IOs",
pgaio_my_backend->num_staged_ios,
dclist_count(&pgaio_my_backend->in_flight_ios),
@@ -1150,6 +1161,8 @@ pgaio_submit_staged(void)
Assert(total_submitted == did_submit);
+ pgstat_count_backend_aio_submitted();
+
pgaio_my_backend->num_staged_ios = 0;
pgaio_debug(DEBUG4,
diff --git a/src/backend/utils/activity/pgstat_backend.c b/src/backend/utils/activity/pgstat_backend.c
index b736b2ccc6f..4ad755f7f18 100644
--- a/src/backend/utils/activity/pgstat_backend.c
+++ b/src/backend/utils/activity/pgstat_backend.c
@@ -40,6 +40,7 @@
static PgStat_BackendPending PendingBackendStats;
static bool backend_has_iostats = false;
static bool backend_has_lockstats = false;
+static bool backend_has_aiostats = false;
/*
* WAL usage counters saved from pgWalUsage at the previous call to
@@ -120,6 +121,74 @@ pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type)
pgstat_report_fixed = true;
}
+/*
+ * Utility routines to report AIO stats for backends, kept here to avoid
+ * exposing PendingBackendStats to the outside world.
+ */
+void
+pgstat_count_backend_aio_start(bool synchronous)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.started++;
+ if (synchronous)
+ PendingBackendStats.aio_counters.executed_sync++;
+ else
+ PendingBackendStats.aio_counters.executed_async++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_self(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_self++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_complete_other(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.completed_other++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_handle_wait(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.handle_waits++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
+void
+pgstat_count_backend_aio_submitted(void)
+{
+ if (!pgstat_tracks_backend_bktype(MyBackendType))
+ return;
+
+ PendingBackendStats.aio_counters.submitted++;
+
+ backend_has_aiostats = true;
+ pgstat_report_fixed = true;
+}
+
/*
* Returns statistics of a backend by proc number.
*/
@@ -326,6 +395,38 @@ pgstat_flush_backend_entry_lock(PgStat_EntryRef *entry_ref)
backend_has_lockstats = false;
}
+/*
+ * Flush out locally pending backend AIO statistics. Locking is managed
+ * by the caller.
+ */
+static void
+pgstat_flush_backend_entry_aio(PgStat_EntryRef *entry_ref)
+{
+ PgStatShared_Backend *shbackendent;
+ PgStat_AioCounters *bktype_shstats;
+
+ if (!backend_has_aiostats)
+ return;
+
+ shbackendent = (PgStatShared_Backend *) entry_ref->shared_stats;
+ bktype_shstats = &shbackendent->stats.aio_counters;
+
+#define AIOSTAT_ACC(fld) \
+ (bktype_shstats->fld += PendingBackendStats.aio_counters.fld)
+ AIOSTAT_ACC(started);
+ AIOSTAT_ACC(executed_sync);
+ AIOSTAT_ACC(executed_async);
+ AIOSTAT_ACC(completed_self);
+ AIOSTAT_ACC(completed_other);
+ AIOSTAT_ACC(handle_waits);
+ AIOSTAT_ACC(submitted);
+#undef AIOSTAT_ACC
+
+ MemSet(&PendingBackendStats.aio_counters, 0, sizeof(PgStat_AioCounters));
+
+ backend_has_aiostats = false;
+}
+
/*
* Flush out locally pending backend statistics
*
@@ -354,6 +455,10 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if ((flags & PGSTAT_BACKEND_FLUSH_LOCK) && backend_has_lockstats)
has_pending_data = true;
+ /* Some AIO data pending? */
+ if ((flags & PGSTAT_BACKEND_FLUSH_AIO) && backend_has_aiostats)
+ has_pending_data = true;
+
if (!has_pending_data)
return false;
@@ -372,6 +477,9 @@ pgstat_flush_backend(bool nowait, uint32 flags)
if (flags & PGSTAT_BACKEND_FLUSH_LOCK)
pgstat_flush_backend_entry_lock(entry_ref);
+ if (flags & PGSTAT_BACKEND_FLUSH_AIO)
+ pgstat_flush_backend_entry_aio(entry_ref);
+
pgstat_unlock_entry(entry_ref);
return false;
@@ -411,6 +519,7 @@ pgstat_create_backend(ProcNumber procnum)
MemSet(&PendingBackendStats, 0, sizeof(PgStat_BackendPending));
backend_has_iostats = false;
backend_has_lockstats = false;
+ backend_has_aiostats = false;
/*
* Initialize prevBackendWalUsage with pgWalUsage so that
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 565d0e70768..fb62a56f3fe 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -1722,6 +1722,66 @@ pg_stat_get_backend_wal(PG_FUNCTION_ARGS)
return (pg_stat_wal_build_tuple(bktype_stats, backend_stats->stat_reset_timestamp));
}
+/*
+ * Returns AIO statistics for a backend with given PID.
+ */
+Datum
+pg_stat_get_backend_aio(PG_FUNCTION_ARGS)
+{
+#define PG_STAT_BACKEND_AIO_COLS 8
+ TupleDesc tupdesc;
+ Datum values[PG_STAT_BACKEND_AIO_COLS] = {0};
+ bool nulls[PG_STAT_BACKEND_AIO_COLS] = {0};
+ int pid;
+ PgStat_Backend *backend_stats;
+ PgStat_AioCounters aio_counters;
+
+ pid = PG_GETARG_INT32(0);
+ backend_stats = pgstat_fetch_stat_backend_by_pid(pid, NULL);
+
+ if (!backend_stats)
+ PG_RETURN_NULL();
+
+ aio_counters = backend_stats->aio_counters;
+
+ /* Initialise attributes information in the tuple descriptor */
+ tupdesc = CreateTemplateTupleDesc(PG_STAT_BACKEND_AIO_COLS);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 1, "started",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 2, "executed_sync",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 3, "executed_async",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 4, "completed_self",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 5, "completed_other",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 6, "handle_waits",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 7, "submitted",
+ INT8OID, -1, 0);
+ TupleDescInitEntry(tupdesc, (AttrNumber) 8, "stats_reset",
+ TIMESTAMPTZOID, -1, 0);
+ TupleDescFinalize(tupdesc);
+ BlessTupleDesc(tupdesc);
+
+ /* Fill values */
+ values[0] = Int64GetDatum(aio_counters.started);
+ values[1] = Int64GetDatum(aio_counters.executed_sync);
+ values[2] = Int64GetDatum(aio_counters.executed_async);
+ values[3] = Int64GetDatum(aio_counters.completed_self);
+ values[4] = Int64GetDatum(aio_counters.completed_other);
+ values[5] = Int64GetDatum(aio_counters.handle_waits);
+ values[6] = Int64GetDatum(aio_counters.submitted);
+
+ if (backend_stats->stat_reset_timestamp != 0)
+ values[7] = TimestampTzGetDatum(backend_stats->stat_reset_timestamp);
+ else
+ nulls[7] = true;
+
+ PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
+}
+
/*
* Returns statistics of WAL activity
*/
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 3cb84359adf..a089860ada4 100644
--- a/src/include/catalog/pg_proc.dat
+++ b/src/include/catalog/pg_proc.dat
@@ -6108,6 +6108,13 @@
proargmodes => '{i,o,o,o,o,o}',
proargnames => '{backend_pid,locktype,waits,wait_time,fastpath_exceeded,stats_reset}',
prosrc => 'pg_stat_get_backend_lock' },
+{ oid => '9082', descr => 'statistics: backend AIO activity',
+ proname => 'pg_stat_get_backend_aio', provolatile => 'v', proparallel => 'r',
+ prorettype => 'record', proargtypes => 'int4',
+ proallargtypes => '{int4,int8,int8,int8,int8,int8,int8,int8,timestamptz}',
+ proargmodes => '{i,o,o,o,o,o,o,o,o}',
+ proargnames => '{backend_pid,started,executed_sync,executed_async,completed_self,completed_other,handle_waits,submitted,stats_reset}',
+ prosrc => 'pg_stat_get_backend_aio' },
{ oid => '6248', descr => 'statistics: information about WAL prefetching',
proname => 'pg_stat_get_recovery_prefetch', prorows => '1', proretset => 't',
provolatile => 'v', prorettype => 'record', proargtypes => '',
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 58a44857f13..64afb2bc082 100644
--- a/src/include/pgstat.h
+++ b/src/include/pgstat.h
@@ -514,6 +514,21 @@ typedef struct PgStat_WalStats
TimestampTz stat_reset_timestamp;
} PgStat_WalStats;
+/* -------
+ * PgStat_AioCounters AIO activity counters
+ * -------
+ */
+typedef struct PgStat_AioCounters
+{
+ PgStat_Counter started;
+ PgStat_Counter executed_sync;
+ PgStat_Counter executed_async;
+ PgStat_Counter completed_self;
+ PgStat_Counter completed_other;
+ PgStat_Counter handle_waits;
+ PgStat_Counter submitted;
+} PgStat_AioCounters;
+
/* -------
* PgStat_Backend Backend statistics
* -------
@@ -524,6 +539,7 @@ typedef struct PgStat_Backend
PgStat_BktypeIO io_stats;
PgStat_WalCounters wal_counters;
PgStat_PendingLock lock_stats;
+ PgStat_AioCounters aio_counters;
} PgStat_Backend;
/* ---------
@@ -542,6 +558,8 @@ typedef struct PgStat_BackendPending
* PGSTAT_KIND_LOCK.
*/
PgStat_PendingLock pending_lock;
+ /* Store the AIO statistics counters */
+ PgStat_AioCounters aio_counters;
} PgStat_BackendPending;
/*
@@ -598,6 +616,13 @@ extern void pgstat_count_backend_io_op(IOObject io_object,
extern void pgstat_count_backend_lock_waits(uint8 locktag_type, PgStat_Counter usecs);
extern void pgstat_count_backend_lock_fastpath_exceeded(uint8 locktag_type);
+/* used by aio.c for AIO stats tracked in backends */
+extern void pgstat_count_backend_aio_start(bool synchronous);
+extern void pgstat_count_backend_aio_complete_self(void);
+extern void pgstat_count_backend_aio_complete_other(void);
+extern void pgstat_count_backend_aio_handle_wait(void);
+extern void pgstat_count_backend_aio_submitted(void);
+
extern PgStat_Backend *pgstat_fetch_stat_backend(ProcNumber procNumber);
extern PgStat_Backend *pgstat_fetch_stat_backend_by_pid(int pid,
BackendType *bktype);
diff --git a/src/include/utils/pgstat_internal.h b/src/include/utils/pgstat_internal.h
index b3dc3ff7d8b..b2092fb42b9 100644
--- a/src/include/utils/pgstat_internal.h
+++ b/src/include/utils/pgstat_internal.h
@@ -706,7 +706,8 @@ extern void pgstat_archiver_snapshot_cb(void);
#define PGSTAT_BACKEND_FLUSH_IO (1 << 0) /* Flush I/O statistics */
#define PGSTAT_BACKEND_FLUSH_WAL (1 << 1) /* Flush WAL statistics */
#define PGSTAT_BACKEND_FLUSH_LOCK (1 << 2) /* Flush lock statistics */
-#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK)
+#define PGSTAT_BACKEND_FLUSH_AIO (1 << 3) /* Flush AIO statistics */
+#define PGSTAT_BACKEND_FLUSH_ALL (PGSTAT_BACKEND_FLUSH_IO | PGSTAT_BACKEND_FLUSH_WAL | PGSTAT_BACKEND_FLUSH_LOCK | PGSTAT_BACKEND_FLUSH_AIO)
extern bool pgstat_flush_backend(bool nowait, uint32 flags);
extern bool pgstat_backend_flush_cb(bool nowait);
diff --git a/src/test/modules/test_aio/t/001_aio.pl b/src/test/modules/test_aio/t/001_aio.pl
index 63cadd64c15..8ecf3d3ad91 100644
--- a/src/test/modules/test_aio/t/001_aio.pl
+++ b/src/test/modules/test_aio/t/001_aio.pl
@@ -1842,6 +1842,37 @@ read_buffers('$table', 0, 4)|,
$psql_c->quit();
}
+# Test per-backend AIO statistics counters
+sub test_aio_stats
+{
+ my $io_method = shift;
+ my $node = shift;
+
+ my $psql = $node->background_psql('postgres', on_error_stop => 0);
+
+ # Reset backend stats, evict relation, then read it back to force
+ # physical IO through the AIO layer.
+ $psql->query_safe(qq(SELECT pg_stat_reset_backend_stats(pg_backend_pid())));
+ $psql->query_safe(qq(SELECT evict_rel('tbl_ok')));
+ $psql->query_safe(qq(SELECT count(*) FROM tbl_ok));
+ $psql->query_safe(qq(SELECT pg_stat_force_next_flush()));
+
+ # started must be > 0 after physical IO
+ my $started = $psql->query_safe(
+ qq(SELECT started FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ cmp_ok($started, '>', 0,
+ "$io_method: AIO stats: started > 0 after physical IO");
+
+ # invariant: started = executed_sync + executed_async
+ my $consistent = $psql->query_safe(
+ qq(SELECT started = executed_sync + executed_async
+ FROM pg_stat_get_backend_aio(pg_backend_pid())));
+ is($consistent, 't',
+ "$io_method: AIO stats: started = executed_sync + executed_async");
+
+ $psql->quit();
+}
+
# Run all tests that for the specified node / io_method
sub test_io_method
{
@@ -1878,6 +1909,7 @@ CHECKPOINT;
test_ignore_checksum($io_method, $node);
test_checksum_createdb($io_method, $node);
test_read_buffers($io_method, $node);
+ test_aio_stats($io_method, $node);
# generic injection tests
SKIP:
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 117e7379f10..6ce3077fa5b 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2329,6 +2329,7 @@ PgStatShared_ReplSlot
PgStatShared_SLRU
PgStatShared_Subscription
PgStatShared_Wal
+PgStat_AioCounters
PgStat_ArchiverStats
PgStat_Backend
PgStat_BackendPending
--
2.34.1
--Pi0/Nu3LVhi0Ij+H--
^ permalink raw reply [nested|flat] 201+ messages in thread
* Add per-backend AIO statistics
@ 2026-07-07 11:02 Bertrand Drouvot <[email protected]>
0 siblings, 2 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-07-07 11:02 UTC (permalink / raw)
To: [email protected]
Hi hackers,
Currently to monitor AIO we can use:
1/ pg_aios that lists all AIO handles that are currently in use. That shows
what's happening right now, but not what has happened.
2/ pg_stat_get_backend_io() that shows how much IO was done, but not how it
was done. There's no way to see whether IOs ran synchronously or
asynchronously, whether a backend was stalling on handle exhaustion, or how
completions are distributed across backends.
This patch helps answering those questions by exposing cumulative per-backend
AIO counters:
- started: total AIO operations initiated
- executed_sync: IOs executed synchronously (fallback path)
- executed_async: IOs submitted asynchronously
- completed_self: IO completions processed by the issuing backend
- completed_other: IO completions processed on behalf of another backend
- handle_waits: times waited for a free AIO handle
- submitted: number of submit calls to the IO method
These counters are useful for understanding and tuning AIO behavior:
- executed_async / started. A ratio near zero means the backend is falling back
to synchronous execution (TOAST chunk fetches, temp buffers, ...).
- a non-zero handle_waits means the backend exhausted all its AIO handles. That
could mean that io_max_concurrency is too low.
- completed_self vs completed_other reveals cross-backend completion patterns.
That helps see how IO completion work is distributed and could help interpret
per backend IO statistics values.
- executed_async / submitted gives the average batch size per submit call.
As far as the technical implementation:
This data can be retrieved with a new system function called
pg_stat_get_backend_aio(), that returns one row based on the PID provided in input.
pgstat_flush_backend() gains a new flag value, able to control the flush of the
AIO stats.
This patch relies mostly on the infrastructure provided by 9aea73fc61d4, that
has introduced backend statistics.
The overhead (4 functions calls and counters increments) kind of follow the same
patterns as pgstat_count_backend_io_op() and I did not observe measurable
regression (I did not expect to). Also that does not add that much memory
per-backend: PgStat_AioCounters is 56 bytes.
There is no "double" counting as a global view to show those counters does not
exist. I think that's better to start with the per-backend side of it and see
if we want to also add a global view. For example, completed_other identifies
which backends did IOs for other backends. Also this allows correlating with
pg_stat_activity and pg_stat_get_backend_io().
Examples based on Franck's blog post [1]:
1/ query the smalldocs table:
postgres=# select count(*),avg(length(data)) from smalldocs;
count | avg
---------+-----------------------
1024000 | 1024.0000000000000000
(1 row)
postgres=# SELECT * FROM pg_stat_get_backend_aio(pg_backend_pid());
started | executed_sync | executed_async | completed_self | completed_other | handle_waits | submitted | stats_reset
---------+---------------+----------------+----------------+-----------------+--------------+-----------+-------------------------------
3125 | 46 | 3079 | 46 | 0 | 0 | 3078 | 2026-07-07 09:28:27.412136+00
We can see that the sequential scan fully benefits from AIO.
2/ query the largedocs table:
postgres=# select count(*),avg(length(data)) from largedocs;
count | avg
-------+----------------------
1000 | 1048576.000000000000
(1 row)
postgres=# SELECT * FROM pg_stat_get_backend_aio(pg_backend_pid());
started | executed_sync | executed_async | completed_self | completed_other | handle_waits | submitted | stats_reset
---------+---------------+----------------+----------------+-----------------+--------------+-----------+-------------------------------
121154 | 121150 | 4 | 121150 | 0 | 0 | 4 | 2026-07-07 09:35:00.504872+00
We can see that the sequential scan bypasses AIO.
Looking forward to your feedback.
[1]: https://dev.to/franckpachot/iouring-buffered-reads-in-postgresql-19-iouring-mcn
Regards,
--
Bertrand Drouvot
PostgreSQL Contributors Team
RDS Open Source Databases
Amazon Web Services: https://aws.amazon.com
^ permalink raw reply [nested|flat] 201+ messages in thread
* Re: Add per-backend AIO statistics
@ 2026-07-08 06:00 Bertrand Drouvot <[email protected]>
parent: Bertrand Drouvot <[email protected]>
1 sibling, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-07-08 06:00 UTC (permalink / raw)
To: [email protected]
Hi,
On Tue, Jul 07, 2026 at 11:02:03AM +0000, Bertrand Drouvot wrote:
> postgres=# select count(*),avg(length(data)) from smalldocs;
> count | avg
> ---------+-----------------------
> 1024000 | 1024.0000000000000000
> (1 row)
>
> postgres=# SELECT * FROM pg_stat_get_backend_aio(pg_backend_pid());
> started | executed_sync | executed_async | completed_self | completed_other | handle_waits | submitted | stats_reset
> ---------+---------------+----------------+----------------+-----------------+--------------+-----------+-------------------------------
> 3125 | 46 | 3079 | 46 | 0 | 0 | 3078 | 2026-07-07 09:28:27.412136+00
>
> We can see that the sequential scan fully benefits from AIO.
>
> 2/ query the largedocs table:
>
> postgres=# select count(*),avg(length(data)) from largedocs;
> count | avg
> -------+----------------------
> 1000 | 1048576.000000000000
> (1 row)
>
> postgres=# SELECT * FROM pg_stat_get_backend_aio(pg_backend_pid());
> started | executed_sync | executed_async | completed_self | completed_other | handle_waits | submitted | stats_reset
> ---------+---------------+----------------+----------------+-----------------+--------------+-----------+-------------------------------
> 121154 | 121150 | 4 | 121150 | 0 | 0 | 4 | 2026-07-07 09:35:00.504872+00
>
> We can see that the sequential scan bypasses AIO.
I was just doing some AIO experiments and was using the new pg_stat_get_backend_aio()
function.
So, while at it, sharing more examples here:
3/ pg_stat_get_backend_aio() and pg_stat_get_backend_io() correlation
postgres=# SELECT executed_sync, executed_async FROM pg_stat_get_backend_aio(pg_backend_pid());
executed_sync | executed_async
---------------+----------------
46 | 3088
(1 row)
postgres=# SELECT object, context, reads, read_bytes FROM pg_stat_get_backend_io(pg_backend_pid());
object | context | reads | read_bytes
---------------+-----------+-------+------------
relation | bulkread | 3088 | 401580032
relation | bulkwrite | 0 | 0
relation | init | 0 | 0
relation | normal | 46 | 376832
relation | vacuum | 0 | 0
temp relation | normal | 0 | 0
wal | init | |
wal | normal | 0 | 0
(8 rows)
We can see that the "executed_sync" matches the reads "normal" context and that
the "executed_async" matches the reads "bulkread" context.
4/ io_uring and multiple backends
postgres=# SELECT a.pid,
(pg_stat_get_backend_aio(a.pid)).completed_other
FROM pg_stat_activity a
WHERE a.backend_type = 'client backend';
pid | completed_other
---------+-----------------
1911889 | 245
1911892 | 511
1911912 | 147
1911933 | 161
(4 rows)
We can see that the backends completed AIO on behalf of other backends, which
makes fully sense in io_uring mode.
5/ io_max_concurrency = 4
postgres=# SELECT started, handle_waits FROM pg_stat_get_backend_aio(pg_backend_pid());
started | handle_waits
---------+--------------
3139 | 3026
(1 row)
We can see that the backend had to wait for free AIO handles on 96% of its IOs.
Regards,
--
Bertrand Drouvot
PostgreSQL Contributors Team
RDS Open Source Databases
Amazon Web Services: https://aws.amazon.com
^ permalink raw reply [nested|flat] 201+ messages in thread
* Re: Add per-backend AIO statistics
@ 2026-07-08 06:52 Michael Paquier <[email protected]>
parent: Bertrand Drouvot <[email protected]>
1 sibling, 2 replies; 201+ messages in thread
From: Michael Paquier @ 2026-07-08 06:52 UTC (permalink / raw)
To: Bertrand Drouvot <[email protected]>; +Cc: [email protected]; Andres Freund <[email protected]>
On Tue, Jul 07, 2026 at 11:02:03AM +0000, Bertrand Drouvot wrote:
> 1/ pg_aios that lists all AIO handles that are currently in use. That shows
> what's happening right now, but not what has happened.
>
> 2/ pg_stat_get_backend_io() that shows how much IO was done, but not how it
> was done. There's no way to see whether IOs ran synchronously or
> asynchronously, whether a backend was stalling on handle exhaustion, or how
> completions are distributed across backends.
While the information may be useful, one thing that sounds very
important to me is how this impacts workloads by default.
Andres is usually able to catch bottlenecks that everybody else is
unable to see, so perhaps checking with him the location of these
extra function calls would be a good first step. Your proposal goes
down to pgaio_io_stage(), pgaio_io_process_completion() and
pgaio_submit_staged() to track these counter increments.
--
Michael
Attachments:
[application/pgp-signature] signature.asc (833B, ../../[email protected]/2-signature.asc)
download
^ permalink raw reply [nested|flat] 201+ messages in thread
* Re: Add per-backend AIO statistics
@ 2026-07-08 08:15 Bertrand Drouvot <[email protected]>
parent: Michael Paquier <[email protected]>
1 sibling, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-07-08 08:15 UTC (permalink / raw)
To: Michael Paquier <[email protected]>; +Cc: [email protected]; Andres Freund <[email protected]>
Hi,
On Wed, Jul 08, 2026 at 03:52:20PM +0900, Michael Paquier wrote:
> On Tue, Jul 07, 2026 at 11:02:03AM +0000, Bertrand Drouvot wrote:
> > 1/ pg_aios that lists all AIO handles that are currently in use. That shows
> > what's happening right now, but not what has happened.
> >
> > 2/ pg_stat_get_backend_io() that shows how much IO was done, but not how it
> > was done. There's no way to see whether IOs ran synchronously or
> > asynchronously, whether a backend was stalling on handle exhaustion, or how
> > completions are distributed across backends.
>
> While the information may be useful,
Thanks for looking at it!
> Andres is usually able to catch bottlenecks that everybody else is
> unable to see, so perhaps checking with him the location of these
> extra function calls would be a good first step. Your proposal goes
> down to pgaio_io_stage(), pgaio_io_process_completion() and
> pgaio_submit_staged() to track these counter increments.
yeah, and also to 1/ confirm that I did understand this area of the AIO code
correctly and 2/ see if other counters could make sense.
Regards,
--
Bertrand Drouvot
PostgreSQL Contributors Team
RDS Open Source Databases
Amazon Web Services: https://aws.amazon.com
^ permalink raw reply [nested|flat] 201+ messages in thread
* Re: Add per-backend AIO statistics
@ 2026-07-08 18:08 Andres Freund <[email protected]>
parent: Michael Paquier <[email protected]>
1 sibling, 1 reply; 201+ messages in thread
From: Andres Freund @ 2026-07-08 18:08 UTC (permalink / raw)
To: Michael Paquier <[email protected]>; +Cc: Bertrand Drouvot <[email protected]>; [email protected]
Hi,
On 2026-07-08 15:52:20 +0900, Michael Paquier wrote:
> On Tue, Jul 07, 2026 at 11:02:03AM +0000, Bertrand Drouvot wrote:
> > 1/ pg_aios that lists all AIO handles that are currently in use. That shows
> > what's happening right now, but not what has happened.
> >
> > 2/ pg_stat_get_backend_io() that shows how much IO was done, but not how it
> > was done. There's no way to see whether IOs ran synchronously or
> > asynchronously, whether a backend was stalling on handle exhaustion, or how
> > completions are distributed across backends.
>
> While the information may be useful, one thing that sounds very
> important to me is how this impacts workloads by default.
> Andres is usually able to catch bottlenecks that everybody else is
> unable to see, so perhaps checking with him the location of these
> extra function calls would be a good first step. Your proposal goes
> down to pgaio_io_stage(), pgaio_io_process_completion() and
> pgaio_submit_staged() to track these counter increments.
I think the overhead might be ok, but I am rather doubtful that all of this
information is actually useful. You're adding quite a few counters for each
IO, do we actually need that?
E.g. what do we gain from counting:
- started (if you want to see the number of IOs that are in progress,
cumulative stats are the wrong tool)
- executed_async (that's just the number of IOs minus executed_sync)
- completed_self (that's just the number of IOs minus executed_other)
Separately, I'm doubtful it makes sense to have only per-backend stats for
this. I think you'd almost always want the stats for exited backend
(e.g. parallel workers) too.
Unfortunately I'm pretty doubtful that pgstat_backend.c is the right
architectural direction. It'll just end up implementing all kinds of stats,
since we'll incrementally want more and more per-backend stats. I think what
we'd want is rather something where for each applicable stats kind we have a
shared counter for all exited backends and then per-backend counters for live
backends, with helpers to aggregate the exited + live stats to a total.
Greetings,
Andres Freund
^ permalink raw reply [nested|flat] 201+ messages in thread
* Re: Add per-backend AIO statistics
@ 2026-07-09 04:19 Bertrand Drouvot <[email protected]>
parent: Andres Freund <[email protected]>
0 siblings, 1 reply; 201+ messages in thread
From: Bertrand Drouvot @ 2026-07-09 04:19 UTC (permalink / raw)
To: Andres Freund <[email protected]>; +Cc: Michael Paquier <[email protected]>; [email protected]
Hi,
On Wed, Jul 08, 2026 at 02:08:00PM -0400, Andres Freund wrote:
> Hi,
>
> On 2026-07-08 15:52:20 +0900, Michael Paquier wrote:
> > On Tue, Jul 07, 2026 at 11:02:03AM +0000, Bertrand Drouvot wrote:
> > > 1/ pg_aios that lists all AIO handles that are currently in use. That shows
> > > what's happening right now, but not what has happened.
> > >
> > > 2/ pg_stat_get_backend_io() that shows how much IO was done, but not how it
> > > was done. There's no way to see whether IOs ran synchronously or
> > > asynchronously, whether a backend was stalling on handle exhaustion, or how
> > > completions are distributed across backends.
> >
> > While the information may be useful, one thing that sounds very
> > important to me is how this impacts workloads by default.
>
>
> > Andres is usually able to catch bottlenecks that everybody else is
> > unable to see, so perhaps checking with him the location of these
> > extra function calls would be a good first step. Your proposal goes
> > down to pgaio_io_stage(), pgaio_io_process_completion() and
> > pgaio_submit_staged() to track these counter increments.
>
> I think the overhead might be ok,
Thanks for the feedback.
> but I am rather doubtful that all of this
> information is actually useful. You're adding quite a few counters for each
> IO, do we actually need that?
>
> E.g. what do we gain from counting:
> - started (if you want to see the number of IOs that are in progress,
> cumulative stats are the wrong tool)
> - executed_async (that's just the number of IOs minus executed_sync)
> - completed_self (that's just the number of IOs minus executed_other)
Yeah, we can remove some fields (as they're derivable).
> Separately, I'm doubtful it makes sense to have only per-backend stats for
> this. I think you'd almost always want the stats for exited backend
> (e.g. parallel workers) too.
Indeed, adding a global view would capture their activity.
> Unfortunately I'm pretty doubtful that pgstat_backend.c is the right
> architectural direction. It'll just end up implementing all kinds of stats,
> since we'll incrementally want more and more per-backend stats. I think what
> we'd want is rather something where for each applicable stats kind we have a
> shared counter for all exited backends and then per-backend counters for live
> backends, with helpers to aggregate the exited + live stats to a total.
That's a very nice proposal that would avoid the double counting. OTOH, that's
also a major re-design that would benefit all existing per-backend stats kinds.
I can see 2 options:
1/
step 1: Implement per-backend AIO stats (like proposed taking into account your
remark about useless, derivable fields) + a global view.
step 2: work on the re-design
2/
step 1: work on the redesign
step 2: Add AIO stats based on the re-design
The pros of 1/ is that step 1 would most probably land in 20, providing more user
visibility (+ it could be used or improved during the AIO write project). Step 2
is a much larger project that might not land in 20.
The cons, would be double counting (as there is no need to try to implement
something like [1] as we are going to re-design anyway).
I'll be tempted to vote for 1/ to provide faster added value. What do you (Andres,
Michael) think?
[1]: https://postgr.es/m/[email protected]
Regards,
--
Bertrand Drouvot
PostgreSQL Contributors Team
RDS Open Source Databases
Amazon Web Services: https://aws.amazon.com
^ permalink raw reply [nested|flat] 201+ messages in thread
* Re: Add per-backend AIO statistics
@ 2026-07-10 04:56 Bertrand Drouvot <[email protected]>
parent: Bertrand Drouvot <[email protected]>
0 siblings, 0 replies; 201+ messages in thread
From: Bertrand Drouvot @ 2026-07-10 04:56 UTC (permalink / raw)
To: Andres Freund <[email protected]>; +Cc: Michael Paquier <[email protected]>; [email protected]
Hi,
On Thu, Jul 09, 2026 at 04:19:26AM +0000, Bertrand Drouvot wrote:
> Hi,
>
> On Wed, Jul 08, 2026 at 02:08:00PM -0400, Andres Freund wrote:
>
> > Unfortunately I'm pretty doubtful that pgstat_backend.c is the right
> > architectural direction. It'll just end up implementing all kinds of stats,
> > since we'll incrementally want more and more per-backend stats. I think what
> > we'd want is rather something where for each applicable stats kind we have a
> > shared counter for all exited backends and then per-backend counters for live
> > backends, with helpers to aggregate the exited + live stats to a total.
>
> That's a very nice proposal that would avoid the double counting. OTOH, that's
> also a major re-design that would benefit all existing per-backend stats kinds.
>
> I can see 2 options:
>
> 1/
>
> step 1: Implement per-backend AIO stats (like proposed taking into account your
> remark about useless, derivable fields) + a global view.
> step 2: work on the re-design
>
> 2/
>
> step 1: work on the redesign
> step 2: Add AIO stats based on the re-design
>
> The pros of 1/ is that step 1 would most probably land in 20, providing more user
> visibility (+ it could be used or improved during the AIO write project). Step 2
> is a much larger project that might not land in 20.
>
> The cons, would be double counting (as there is no need to try to implement
> something like [1] as we are going to re-design anyway).
>
> I'll be tempted to vote for 1/ to provide faster added value. What do you (Andres,
> Michael) think?
Actually, there is no rush to merge the per-backend AIO stats (we still have
plenty of time for 20). So let's try option 2 and implement the new design first
and see where it goes. I'll create a dedicated thread once ready.
Regards,
--
Bertrand Drouvot
PostgreSQL Contributors Team
RDS Open Source Databases
Amazon Web Services: https://aws.amazon.com
^ permalink raw reply [nested|flat] 201+ messages in thread
end of thread, other threads:[~2026-07-10 04:56 UTC | newest]
Thread overview: 201+ messages (download: mbox mbox.gz follow: Atom feed)
-- links below jump to the message on this page --
2023-07-26 10:49 [PATCH v3 4/7] Row pattern recognition patch (executor). Tatsuo Ishii <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-06-11 09:45 [PATCH v1] Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-07-07 11:02 Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-07-08 06:00 ` Re: Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-07-08 06:52 ` Re: Add per-backend AIO statistics Michael Paquier <[email protected]>
2026-07-08 08:15 ` Re: Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-07-08 18:08 ` Re: Add per-backend AIO statistics Andres Freund <[email protected]>
2026-07-09 04:19 ` Re: Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
2026-07-10 04:56 ` Re: Add per-backend AIO statistics Bertrand Drouvot <[email protected]>
This inbox is served by agora; see mirroring instructions
for how to clone and mirror all data and code used for this inbox