Database administrator comparing cached and refreshed PostgreSQL statistics across terminal sessions.

Why PostgreSQL Statistics Stay Stale Inside a Transaction

Tue, Dec 1, 2026

A PostgreSQL monitoring collector can produce a result that looks impossible until the evidence is separated into the right layers. Imagine a writer inserts three known rows and commits. A fresh observer later sees those rows and reports the table’s cumulative n_tup_ins counter as 4. Yet a monitoring connection that queried the counter before the write still reports 1.

That result does not, by itself, mean PostgreSQL lost the writer’s statistics, that the commit failed, or that ordinary MVCC visibility is broken. PostgreSQL’s cumulative statistics have two relevant timing boundaries: a producer first has to publish locally accumulated statistics to shared memory, and a reader may then retain previously fetched statistics according to stats_fetch_consistency. PostgreSQL documents both behaviors separately. Publication is not instantaneous, while the default cache mode can retain an object’s first-accessed cumulative statistics until the reader transaction ends or its statistics state is explicitly cleared.

This playbook isolates those two mechanisms with three separately identified backends: W, the writer; M, the measured monitoring connection; and F, a fresh observer used as an independent publication barrier. The proposed baseline is an owned, disposable, single-node PostgreSQL 18.7 database with psql 18.7. PostgreSQL 18.7 was released November 12, 2026; that fixes the proposed patch baseline, not the historical introduction of the statistics behavior discussed here. No database laboratory was executed, so every case below remains EXPECTED / NOT EXECUTED and no PID, timestamp, latency, or observed value is fabricated.

Define the freshness claim and its limits

The claim under test is deliberately narrower than “statistics are fresh.” For this playbook, a collector policy satisfies the freshness requirement when after F has independently confirmed that the intended cumulative value is published, M’s next intended sample returns that published value under the collector’s declared policy.

That wording matters. W establishes authored database work. F establishes the publication boundary. M establishes reader behavior. Without all three, an old value can be attributed to the wrong layer.

The investigation measures only one cumulative relation statistic: n_tup_ins. PostgreSQL defines it as the total number of rows inserted for the table. It is not the same statistic as n_live_tup, which PostgreSQL documents as an estimate of live rows. Nor does an n_tup_ins value prove the exact set of committed rows that should exist in an arbitrary production workload.

Three different monitoring properties must therefore remain separate.

Property

Question

Fresh retrieval

Does M fetch statistics published before the intended sample?

Coherent statistics sampling

Are several statistics deliberately held at a defined reader-side boundary?

Exact ordinary-data visibility

Which committed table rows are visible under M’s MVCC isolation snapshot?

The laboratory uses permanent case-specific tables in an owned disposable schema, a single controlled writer, no triggers, no extensions, and no unrelated writers. Every table starts with one authored seed tuple. W then contributes exactly three additional successful inserts. That controlled fixture makes 4 a useful expected n_tup_ins value, but only because retries, aborts, competing writers, resets, and other mutations are excluded.

This is a different problem from PostgreSQL query identity and workload grouping: knowing which workload a measurement describes does not establish when a cumulative table statistic was published or whether a reader has retained an older value.

The eventual operational decisions are ACCEPT a collector policy demonstrated against its requirement, REPAIR a reader lifecycle or configuration problem, RERUN a case whose controls were compromised, or HOLD when publication or required evidence remains unresolved. Because this playbook contains no executed PostgreSQL run, none of those acceptance decisions is claimed as an observed result.

Separate producer publication from reader caching

PostgreSQL’s cumulative statistics architecture creates the first freshness boundary on the producer side. Server processes accumulate statistics locally and update shared statistics at appropriate intervals. PostgreSQL states that an individual process normally flushes accumulated statistics just before going idle, but no more frequently than PGSTAT_MIN_INTERVAL, which is one second unless changed when PostgreSQL is built. A query or transaction still in progress therefore does not necessarily appear immediately in displayed cumulative totals.

The one-second value is a minimum interval limiting flush frequency, not a documented upper bound saying every contribution must become observable within one second. A test that sleeps one second and then assumes publication has occurred is therefore not strong enough. The publication barrier in this protocol is an actual F result that matches both the intended counter and the ordinary row manifest.

After publication, a second timing boundary exists inside the reader. PostgreSQL 18 documents three behaviors for stats_fetch_consistency; the default is cache. Changing this setting within a transaction discards retained cumulative-statistics state.

stats_fetch_consistency

Reader behavior within a transaction

cache

The first access to an object’s statistics caches that object’s statistics until transaction end or pg_stat_clear_snapshot().

snapshot

The first cumulative-statistics access captures all accessible statistics in the current database and retains them until transaction end or clearing.

none

Each statistics access refetches counters from shared memory.

These modes solve reader-side problems. They do not make a producer publish activity that remains local. Setting none cannot retrieve statistics that W has not yet put into shared statistics. Calling pg_stat_clear_snapshot() cannot force W to publish either. Both mechanisms only affect what M does with already accessible cumulative statistics.

That producer-versus-reader distinction is the key diagnostic ordering. If F has not yet demonstrated 4, M returning 1 does not isolate a reader cache problem. Once F has demonstrated 4, an M result of 1 under a controlled open cache transaction becomes evidence about M’s retained statistics state rather than evidence that the producer is still unpublished.

A published counter is not an exact live-row census

n_tup_ins is a cumulative count of inserted tuples. n_live_tup is an estimated live-row statistic. Neither should be substituted for an exact row oracle in this laboratory. PostgreSQL also exposes pg_stat_xact_* views whose current-transaction behavior differs from the shared cumulative views; they are intentionally outside this matrix.

The exact data oracle is instead the authored tuple manifest:

(0, 'seed')
(1, 'one')
(2, 'two')
(3, 'three')

The expected counter of 4 is meaningful only because each case uses a newly created relation, one successful seed insertion, one controlled successful three-row writer payload, and no other inserts. Do not turn that fixture property into a general claim that n_tup_ins establishes committed-row completeness.

Pin the runtime and identify the three sessions

The proposed baseline is PostgreSQL server 18.7 and psql 18.7 on one disposable single-node database. The actual runtime remains NOT RECORDED / NOT EXECUTED for this playbook. An executed qualification must capture what is really installed rather than converting the proposed server_version_num of 180007 into evidence. PostgreSQL’s November 12, 2026 release notes establish 18.7 as a real documented patch release.

Open three terminals using psql without startup files and with script errors configured to stop processing:

psql -X -v ON_ERROR_STOP=1 "$DATABASE_URL"

-X prevents psql startup files from changing the test environment. ON_ERROR_STOP makes noninteractive processing stop after errors instead of silently continuing; actual stderr and process status should be retained whenever scripts are used. psql’s AUTOCOMMIT variable defaults to on, meaning a SQL command outside an explicit transaction is committed after successful completion.

In each terminal, inspect rather than assume the client state:

\echo :AUTOCOMMIT
\conninfo

Then capture the server-side identity:

SELECT
    version(),
    current_setting('server_version_num') AS server_version_num,
    current_database()                    AS database_name,
    session_user,
    current_user,
    pg_backend_pid()                      AS backend_pid,
    current_setting('track_counts')       AS track_counts,
    current_setting('transaction_isolation') AS isolation,
    current_setting('stats_fetch_consistency') AS stats_fetch_consistency,
    inet_server_addr()                    AS server_addr,
    inet_server_port()                    AS server_port;

track_counts must be confirmed because it controls collection of database activity statistics; PostgreSQL documents it as enabled by default, but a validation should record the installed setting instead of inheriting that assumption.

Label the connections W, M, and F in the evidence ledger and verify that their backend PIDs differ while database and endpoint identify the same test database. Save M’s original session-level stats_fetch_consistency, then establish the measured baseline:

-- M
SET SESSION stats_fetch_consistency = 'cache';
SHOW stats_fetch_consistency;

-- F
SET SESSION stats_fetch_consistency = 'none';
SHOW stats_fetch_consistency;

F remains one identified backend and performs its polling as individually completed autocommit requests.

Keep the first statistics access under control

Before any measured transaction, establish the installed relation-view mapping rather than treating development-branch source as patch-level proof:

SELECT pg_get_viewdef(
    'pg_catalog.pg_stat_all_tables'::regclass,
    true
);

SELECT to_regprocedure(
    'pg_catalog.pg_stat_get_tuples_inserted(oid)'
);

PostgreSQL’s documentation explicitly advises consulting standard-view definitions to identify their underlying cumulative-statistics access functions, and documents that per-table functions take a relation OID.

The executed preflight must verify that n_tup_ins maps to the installed pg_catalog.pg_stat_get_tuples_inserted(oid) accessor. If that mapping cannot be demonstrated, classify the run HOLD. In two-table cases, use direct single-OID calls such as:

SELECT pg_catalog.pg_stat_get_tuples_inserted(
    'stats_lab.s06_a'::regclass
);

A broad cumulative-statistics view scan before the intended first access can invalidate the experiment.

Build clean cases and an observable publication barrier

Use a database owned for destructive testing. The setup deliberately rejects a pre-existing stats_lab namespace: do not add IF NOT EXISTS, truncate an old fixture, or quietly recycle a previous relation. New object identity is part of the baseline.

CREATE SCHEMA stats_lab;

CREATE TABLE stats_lab.s01   (id integer PRIMARY KEY, marker text NOT NULL);
CREATE TABLE stats_lab.s02   (id integer PRIMARY KEY, marker text NOT NULL);
CREATE TABLE stats_lab.s03   (id integer PRIMARY KEY, marker text NOT NULL);
CREATE TABLE stats_lab.s04   (id integer PRIMARY KEY, marker text NOT NULL);
CREATE TABLE stats_lab.s05   (id integer PRIMARY KEY, marker text NOT NULL);
CREATE TABLE stats_lab.s06_a (id integer PRIMARY KEY, marker text NOT NULL);
CREATE TABLE stats_lab.s06_b (id integer PRIMARY KEY, marker text NOT NULL);
CREATE TABLE stats_lab.s07_a (id integer PRIMARY KEY, marker text NOT NULL);
CREATE TABLE stats_lab.s07_b (id integer PRIMARY KEY, marker text NOT NULL);
CREATE TABLE stats_lab.s08_a (id integer PRIMARY KEY, marker text NOT NULL);
CREATE TABLE stats_lab.s08_b (id integer PRIMARY KEY, marker text NOT NULL);
CREATE TABLE stats_lab.s09   (id integer PRIMARY KEY, marker text NOT NULL);
CREATE TABLE stats_lab.s10   (id integer PRIMARY KEY, marker text NOT NULL);

Seed every relation exactly once before its case begins:

INSERT INTO stats_lab.s01 VALUES (0, 'seed');
-- Repeat exactly once for s02, s03, s04, s05,
-- s06_a, s06_b, s07_a, s07_b, s08_a, s08_b, s09, and s10.

For each case, F must establish the clean baseline before M’s measured access. F performs a direct counter request and an ordinary row request as separate completed autocommit statements:

SELECT pg_catalog.pg_stat_get_tuples_inserted(
    'stats_lab.s02'::regclass
) AS n_tup_ins;
SELECT id, marker
FROM stats_lab.s02
ORDER BY id;

The expected baseline is n_tup_ins = 1 and exactly (0,'seed'). If the counter is anything else, if the tuple differs, or if an existing relation was reused, stop that case. A baseline anomaly is not evidence about cache semantics.

W’s common payload is:

BEGIN;

INSERT INTO stats_lab.s02 (id, marker)
VALUES (1, 'one'), (2, 'two'), (3, 'three');

COMMIT;

For S06–S08, W executes identical inserts into both A and B before the same COMMIT.

The authored data oracle after commit is:

SELECT id, marker
FROM stats_lab.s02
ORDER BY id;

Expected complete output:

0 | seed
1 | one
2 | two
3 | three

Capture all four tuples. SELECT count(*) alone cannot show that the intended identities and markers are present.

After W’s COMMIT command has completed successfully, F begins the publication check. The protocol uses a bounded wall-clock deadline of 30 seconds, but the 30 seconds is not a PostgreSQL freshness guarantee. It is merely a test decision boundary. Reissue the direct counter SELECT as a new autocommit request each time, with modest client-side pacing, and separately repeat the ordered row query. The barrier is achieved only when F has recorded both n_tup_ins = 4 and the exact four-row manifest.

A convenient interactive psql pattern is to issue one query, wait briefly at the client, and issue the next, while preserving the same F connection and AUTOCOMMIT on. An automation harness may do the same over one connection. Do not put the loop inside a server-side DO block or a single explicit transaction.

Also avoid treating one multi-statement psql -c string as several independent polling transactions. PostgreSQL’s psql documentation states that the server receives one SQL command string supplied through a single -c as one request and executes multiple commands in that string as one transaction unless explicit transaction boundaries divide it.

Only after the recorded F match may the operator write a barrier acknowledgment into the case ledger and permit M’s second measurement. Neither W’s successful COMMIT, a fixed sleep, nor W appearing idle is a substitute.

If 30 seconds expires without both F conditions being demonstrated, classify the case HOLD. The evidence then says publication was not confirmed within the test window. It does not establish lost data, a PostgreSQL defect, or reader caching.

Reproduce a cached counter after publication

S01: EXPECTED / NOT EXECUTED. S01 is the short-transaction control. M is in session-level cache mode but does not hold an explicit transaction open.

M first queries the published seed value:

SELECT pg_catalog.pg_stat_get_tuples_inserted(
    'stats_lab.s01'::regclass
);
Expected: 1.

That statement’s autocommit transaction ends. W then inserts the three authored rows and commits. F independently confirms 4 plus the complete row manifest. Only then does M issue a new autocommit request:

SELECT pg_catalog.pg_stat_get_tuples_inserted(
    'stats_lab.s01'::regclass
);

Expected: 4. In default cache behavior, cached cumulative statistics are retained through the current transaction, not across a completed transaction into the next autocommit sample.

S02: EXPECTED / NOT EXECUTED. This is the controlled stale-reader case.

-- M
BEGIN ISOLATION LEVEL READ COMMITTED;
SET LOCAL stats_fetch_consistency = 'cache';

SELECT pg_catalog.pg_stat_get_tuples_inserted(
    'stats_lab.s02'::regclass
);

Expected first M value: 1. Keep M’s transaction open.

W executes its three-row insert and commits. F then confirms counter 4 and all four ordinary rows. M now rereads the same object without ending the transaction or clearing cumulative-statistics state:

SELECT pg_catalog.pg_stat_get_tuples_inserted(
    'stats_lab.s02'::regclass
);
Expected: 1.

That result would demonstrate failure of a collector contract that assumed each SQL statement in the transaction refetched the cumulative counter. It would not demonstrate failed publication because F has already established publication. PostgreSQL documents the default cache behavior as retaining an object’s first-accessed cumulative statistics until transaction end unless explicitly cleared.

The same operational discipline, separating state with different lifetimes, appears in Refonte’s article on how to separate sequence state from rollback evidence. The sequence mechanics are outside this article; the relevant operational principle is that one successful transaction signal should not be asked to prove a different state transition.

Compare the stale counter with committed row identities

Still inside M’s S02 READ COMMITTED transaction, issue a separate ordinary-data request after the second counter request:

SELECT id, marker
FROM stats_lab.s02
ORDER BY id;

Expected:

0 | seed
1 | one
2 | two
3 | three

So the expected S02 juxtaposition is n_tup_ins = 1 while the ordinary data query returns all four rows.

That is not contradictory. PostgreSQL’s READ COMMITTED isolation takes a new ordinary-data snapshot for each command; two successive SELECT statements in one transaction can therefore see different committed database states when another transaction commits between them. Separately, PostgreSQL’s cumulative-statistics cache can retain the earlier per-object statistics value for the duration of M’s transaction.

Record the counter request and ordinary-data request independently and in order. Combining them conceptually into “the monitor queried the table” destroys the distinction the experiment is designed to establish.

Refresh by clearing or ending the reader transaction

S03: EXPECTED / NOT EXECUTED. Recreate the S02 ordering on fresh stats_lab.s03: M opens READ COMMITTED, sets local cache, reads 1; W commits the three-row payload; F confirms 4 and the manifest; M rereads and is expected still to see 1.

Then M executes the clearing operation as its own request:

SELECT pg_stat_clear_snapshot();

PostgreSQL documents pg_stat_clear_snapshot() as discarding the current transaction’s cumulative-statistics snapshot or cached information. It does not reset the shared counters. The next cumulative-statistics access may therefore fetch again under the current mode.

Now issue a separate request:

SELECT pg_catalog.pg_stat_get_tuples_inserted(
    'stats_lab.s03'::regclass
);

Expected M result: 4. F remains 4, and the ordinary four-row manifest remains intact. Clearing changed M’s retained reader state; it neither reset nor republished the shared cumulative counter.

S04: EXPECTED / NOT EXECUTED. Produce the same controlled M=1, F=4 mismatch on stats_lab.s04, but repair the reader lifecycle by ending M’s read transaction:

COMMIT;

BEGIN ISOLATION LEVEL READ COMMITTED;
SHOW stats_fetch_consistency;

SELECT pg_catalog.pg_stat_get_tuples_inserted(
    'stats_lab.s04'::regclass
);

Expected result: 4, assuming M’s session setting is the planned cache baseline. Transaction completion discarded the old transaction’s cached object statistic; the next transaction therefore establishes new reader state.

Which policy better expresses the collector depends on its intended sampling boundary. If one polling cycle conceptually consists of one short sample, ending the transaction after that sample is easy to reason about and difficult to forget. If a collector intentionally holds a transaction while periodically refreshing selected cumulative statistics, an explicit clearing boundary can state that lifecycle directly.

Neither policy forces producer publication. That is why F’s barrier remains mandatory in both cases.

Read published counters again with none

S05: EXPECTED / NOT EXECUTED. Start with a fresh seeded stats_lab.s05, baseline-confirmed at 1.

M opens one READ COMMITTED transaction but chooses none locally:

BEGIN ISOLATION LEVEL READ COMMITTED;
SET LOCAL stats_fetch_consistency = 'none';

SELECT pg_catalog.pg_stat_get_tuples_inserted(
    'stats_lab.s05'::regclass
);
Expected first result: 1.

W commits three rows. F confirms 4 and the exact manifest. M remains in the same transaction and performs no clear operation:

SELECT pg_catalog.pg_stat_get_tuples_inserted(
    'stats_lab.s05'::regclass
);
Expected second result: 4.

PostgreSQL defines none as refetching counters from shared memory on every cumulative-statistics access. The documentation calls it particularly suitable when a monitoring system accesses values once and does not need caching. That recommendation should not be inflated into “none guarantees freshness”: it cannot retrieve a producer contribution that has not yet been published to shared statistics.

none is therefore a strong candidate for short monitoring reads whose requirement is “get what is in shared statistics now.” It is less appropriate when an analysis deliberately needs several cumulative-statistics reads to remain stable while the operator compares them. That is a coherence requirement, not a freshness failure.

Expose mixed observation times in cache mode

S06: EXPECTED / NOT EXECUTED. This case demonstrates why a successful monitoring query does not automatically establish a single observation time across several table counters.

Both stats_lab.s06_a and stats_lab.s06_b begin with one published seed insertion. F confirms 1 and the seed manifest independently for both.

M opens a READ COMMITTED transaction with local cache:

BEGIN ISOLATION LEVEL READ COMMITTED;
SET LOCAL stats_fetch_consistency = 'cache';

SELECT pg_catalog.pg_stat_get_tuples_inserted(
    'stats_lab.s06_a'::regclass
) AS a_n_tup_ins;
Expected: A=1. M must not access B yet.

W now inserts the three authored rows into both relations in one transaction:

BEGIN;

INSERT INTO stats_lab.s06_a (id, marker)
VALUES (1,'one'), (2,'two'), (3,'three');

INSERT INTO stats_lab.s06_b (id, marker)
VALUES (1,'one'), (2,'two'), (3,'three');

COMMIT;

F independently confirms A=4, B=4, and both complete manifests.

M then performs two deliberate requests in this order:

SELECT pg_catalog.pg_stat_get_tuples_inserted(
    'stats_lab.s06_a'::regclass
) AS a_n_tup_ins;
Expected A=1.
SELECT pg_catalog.pg_stat_get_tuples_inserted(
    'stats_lab.s06_b'::regclass
) AS b_n_tup_ins;
Expected B=4.

Under cache, PostgreSQL caches statistics for each object when that object is first accessed, so independently first-accessed objects in one transaction can reflect different retrieval times.

The collector implication is important: “all SQL statements succeeded” does not prove that A and B were observed at a common statistics boundary. cache can provide repeatability per accessed object while still allowing later first accesses to newer objects to see newer shared statistics.

Prevent an accidental first access to the second table

S06 is only interpretable when B really was untouched before F’s barrier. That is why preflight resolved the installed accessor and the measured transaction uses single-OID function calls.

Do not execute a broad pg_stat_user_tables or pg_stat_all_tables inspection inside M and later call it harmless setup. Depending on which cumulative statistics are accessed, such inspection can alter the very first-access sequence being tested. Record every cumulative-statistics request M makes.

If a transcript reveals that B was accessed before the intended point, classify S06 RERUN. An unexpected B result after contaminated access order is not evidence against PostgreSQL’s documented cache semantics; it is evidence that the case did not test the authored condition.

Rebuild a deliberate statistics snapshot

S07: EXPECTED / NOT EXECUTED. Seed and publish s07_a and s07_b at 1. M begins a transaction and chooses snapshot mode:

BEGIN ISOLATION LEVEL READ COMMITTED;
SET LOCAL stats_fetch_consistency = 'snapshot';

Before touching cumulative statistics, inspect the statistics-snapshot timestamp in its own request:

SELECT pg_stat_get_snapshot_timestamp();
Expected: NULL.

Now access only A:

SELECT pg_catalog.pg_stat_get_tuples_inserted(
    'stats_lab.s07_a'::regclass
);
Expected A=1. Then separately:
SELECT pg_stat_get_snapshot_timestamp();
Expected: non-NULL.

PostgreSQL documents snapshot as capturing all accessible statistics for the current database on the first cumulative-statistics access and retaining them until transaction end or explicit clearing. pg_stat_get_snapshot_timestamp() returns the timestamp of the current statistics snapshot, or NULL when no such snapshot has been taken.

W then inserts into both tables and commits. F confirms 4/4 plus both manifests.

M reads A and B after that barrier:

SELECT pg_catalog.pg_stat_get_tuples_inserted(
    'stats_lab.s07_a'::regclass
);

SELECT pg_catalog.pg_stat_get_tuples_inserted(
    'stats_lab.s07_b'::regclass
);

Expected: 1 and 1. B was not directly queried before W, but the first cumulative-statistics access in snapshot mode established the broader database statistics snapshot that includes it.

S08: EXPECTED / NOT EXECUTED. Repeat the same setup using s08_a and s08_b. Preserve the pre-write pair and the initial non-NULL snapshot timestamp. After W commits and F confirms 4/4, clear M’s statistics state:

SELECT pg_stat_clear_snapshot();

Then, in a separate request:

SELECT pg_stat_get_snapshot_timestamp();
Expected: NULL.

Rebuild the snapshot by accessing A:

SELECT pg_catalog.pg_stat_get_tuples_inserted(
    'stats_lab.s08_a'::regclass
);
Expected A=4.

Capture the rebuilt timestamp separately:

SELECT pg_stat_get_snapshot_timestamp();
Expected: non-NULL.

Finally:

SELECT pg_catalog.pg_stat_get_tuples_inserted(
    'stats_lab.s08_b'::regclass
);
Expected B=4.

Snapshot mode is therefore useful when the collector values a deliberate reader-side coherence boundary across accessible cumulative statistics. Clearing and rebuilding moves that boundary forward. It does not certify that every producer contribution represented in that snapshot was generated at one instantaneous global moment. PostgreSQL’s producer publication remains asynchronous.

Interpret the snapshot timestamp without overclaiming

Always issue the timestamp checks and counter reads as separate SQL requests. Do not make the experiment depend on SELECT-list expression evaluation order.

A NULL result from pg_stat_get_snapshot_timestamp() under cache or none does not itself prove that a counter is newly fetched; the function specifically describes the current statistics snapshot associated with snapshot mode. Conversely, a non-NULL timestamp is not a per-producer publication timestamp.

Do not derive “W’s statistics were 300 ms old,” “every table is as of this exact instant,” or any publication-latency promise from that timestamp. It marks reader-side snapshot creation, not the age of every producer contribution incorporated into shared statistics.

Keep statistics refresh separate from MVCC visibility

S10: EXPECTED / NOT EXECUTED. This case deliberately gives ordinary data and cumulative statistics different refresh behavior.

F first confirms stats_lab.s10 at counter 1 with only (0,'seed'). M begins REPEATABLE READ:

BEGIN ISOLATION LEVEL REPEATABLE READ;
SET LOCAL stats_fetch_consistency = 'cache';

M establishes its ordinary-data snapshot first:

SELECT id, marker
FROM stats_lab.s10
ORDER BY id;

Expected: seed row only.

M then reads the cumulative counter:

SELECT pg_catalog.pg_stat_get_tuples_inserted(
    'stats_lab.s10'::regclass
);
Expected: 1.

W inserts the three rows and commits. F, operating independently, confirms counter 4 and all four row identities.

M now clears cumulative-statistics state:

SELECT pg_stat_clear_snapshot();

Then M performs separate requests:

SELECT pg_catalog.pg_stat_get_tuples_inserted(
    'stats_lab.s10'::regclass
);

Expected counter: 4.

SELECT id, marker
FROM stats_lab.s10
ORDER BY id;

Expected ordinary rows: still only (0,'seed').

PostgreSQL’s REPEATABLE READ ordinary-data snapshot does not advance to include concurrent commits made after the transaction’s snapshot was established. Clearing cumulative-statistics state, however, controls the statistics reader and does not replace that MVCC snapshot.

After M ends its transaction:

COMMIT;

SELECT id, marker
FROM stats_lab.s10
ORDER BY id;

A fresh ordinary-data request is expected to see all four rows.

This is why monitoring validation must validate index state in the right transaction or, in this article’s different mechanism, validate statistics and ordinary data in the transaction whose visibility rules you actually intend to test.

Reconcile the complete evidence ledger

All outcomes below are EXPECTED / NOT EXECUTED. The matrix is a qualification plan, not an observed-results table.

Case

M mode

M transaction condition

F publication barrier

Expected M counter after barrier

Expected ordinary rows where tested

Status

S01

cache

New autocommit transaction for second sample

4 + manifest

4

Not specified

EXPECTED / NOT EXECUTED

S02

cache

Same open READ COMMITTED transaction

4 + manifest

1

Four rows

EXPECTED / NOT EXECUTED

S03

cache

Same transaction, then pg_stat_clear_snapshot()

4 + manifest

4 after clear

Four rows

EXPECTED / NOT EXECUTED

S04

cache

Stale transaction ended; new transaction begins

4 + manifest

4

Not specified

EXPECTED / NOT EXECUTED

S05

none

Same open READ COMMITTED transaction

4 + manifest

4

Not specified

EXPECTED / NOT EXECUTED

S06

cache

A accessed before write; B first accessed after barrier

4/4 + both manifests

A=1, B=4

Both manifests via F

EXPECTED / NOT EXECUTED

S07

snapshot

Snapshot created before W

4/4 + both manifests

A=1, B=1

Not specified

EXPECTED / NOT EXECUTED

S08

snapshot

Old snapshot cleared and rebuilt after barrier

4/4 + both manifests

A=4, B=4

Not specified

EXPECTED / NOT EXECUTED

S09

cache → none

Setting changed inside same transaction

4 + manifest

4

Not specified

EXPECTED / NOT EXECUTED

S10

cache

REPEATABLE READ; stats cleared after barrier

4 + manifest

4

Seed only until M commits

EXPECTED / NOT EXECUTED

Do not add an “observed result” column and fill it from this table. An executed evidence ledger must retain actual output independently of authored expectations.

For every case, record: actual server and psql versions; endpoint, database, role, backend PID, and W/M/F identity; track_counts; M’s isolation and stats_fetch_consistency; psql autocommit state; table identity; exact SQL and command order; baseline counter and tuples; W’s completed commit acknowledgment; F’s polling requests; the first qualifying F counter and full row result; whether the deadline expired; M’s pre- and post-barrier counters; ordinary ordered tuples where required; snapshot timestamps where applicable; and all actual errors and process statuses.

The evidence must also preserve which cumulative-statistics object M touched first. S06–S08 are access-order experiments; a broad statistics query can silently destroy their premise.

Classify evidence defects by layer. If M reads an old counter before F has demonstrated publication, reader retention has not been isolated: HOLD. If the initial counter is not 1, the table was reused, the fixture contains unexpected rows, a statistics reset or server restart intruded, another writer touched the table, or W’s commit cannot be established, the controlled attribution is invalid: normally RERUN after rebuilding a clean case.

If S06 accidentally accessed B before W’s commit, RERUN. If F times out, HOLD, because publication remains unresolved. If an SQL command errors, retain the actual error and client status rather than continuing and converting the remaining expected values into apparent evidence.

Preserve raw outputs before dropping the schema. Reconcile the ordered tuple manifest value by value. A count of four is weaker than evidence that IDs 0, 1, 2, and 3 have exactly the authored markers.

Repair the collector and verify configuration scope

S09: EXPECTED / NOT EXECUTED. This case tests a settings repair inside the same reader transaction.

M begins from its session baseline:

SET SESSION stats_fetch_consistency = 'cache';
SHOW stats_fetch_consistency;

BEGIN ISOLATION LEVEL READ COMMITTED;

SELECT pg_catalog.pg_stat_get_tuples_inserted(
    'stats_lab.s09'::regclass
);

Expected first result: 1.

W commits the three-row payload. F confirms counter 4 and the four-row manifest. M remains in the same transaction and now changes only its local mode:

SET LOCAL stats_fetch_consistency = 'none';

Then:

SELECT pg_catalog.pg_stat_get_tuples_inserted(
    'stats_lab.s09'::regclass
);

Expected: 4.

PostgreSQL documents that changing stats_fetch_consistency within a transaction discards retained statistics state, and none refetches counters from shared memory on access.

End M’s transaction and verify scope:

COMMIT;
SHOW stats_fetch_consistency;

Expected: cache.

SET LOCAL lasts only until the current transaction ends; afterwards the session-level value applies again. PostgreSQL also documents that using SET LOCAL outside a transaction emits a warning and has no effect.

This distinction matters in connection pools. Changing an administrator’s psql session does not configure unrelated pool connections. The intended collector policy belongs in the code or connection initialization path that actually owns each monitoring session. That is also where teams should automate database checks with explicit evidence, rather than relying on an operator’s one-off connection state.

A collector can therefore choose among three defensible patterns: make each sample a short autocommit transaction, deliberately clear statistics state at a documented refresh boundary, or establish the required stats_fetch_consistency on every actual collector connection. The correct choice follows the collector’s freshness-versus-coherence contract.

Restore settings without resetting shared counters

After the case, end the owned read transaction and restore M’s original session setting if the qualification changed it:

RESET stats_fetch_consistency;
SHOW stats_fetch_consistency;

Or restore the exact recorded original value explicitly if that is the laboratory policy.

Preserve evidence before cleanup, then begin a clean sample and repeat the publication/freshness validation. Do not repair a demonstrated reader-cache lifecycle problem by replaying business inserts, resetting cumulative statistics, or restarting PostgreSQL. Those actions alter unrelated state and weaken attribution.

If F still cannot confirm producer publication, keep the decision HOLD and investigate that separate publication layer rather than masking it with reader-side changes.

Make the decision and assign operational ownership

The qualification result is not “the SELECT succeeded.” It is whether the collector’s demonstrated lifecycle satisfies its declared freshness or coherence requirement with complete evidence.

Decision

Use it when

ACCEPT

The relevant case has complete evidence, F proves publication, M behaves as required under the chosen lifecycle, and the policy matches the collector’s freshness/coherence requirement.

REPAIR

Evidence demonstrates a reader lifecycle or configuration error, such as an unintentionally long cache transaction or a setting applied to the wrong scope.

RERUN

The baseline, fixture, first-access order, session identity, or another experimental control was compromised.

HOLD

Producer publication remains unconfirmed, required evidence is missing, or contradictory evidence prevents attribution.

Operational ownership should be equally explicit. The DBA owns interpretation of PostgreSQL’s cumulative-statistics contract, installed-version review, accessor preflight, and safe laboratory boundaries. The collector maintainer owns connection lifecycle, transaction boundaries, pool initialization, autocommit behavior, and where stats_fetch_consistency or clearing logic is applied. The service owner defines whether a sample prioritizes latest retrievable shared statistics, repeatable per-object readings, or a deliberately coherent statistics snapshot.

Those responsibilities overlap with broader database monitoring and operational responsibilities, but the acceptance decision here remains narrow: prove the collector behavior you actually depend on.

Revalidate after PostgreSQL version changes, driver or pool changes, autocommit changes, connection initialization changes, stats_fetch_consistency changes, transaction-scope changes, or query-shape changes that alter which cumulative-statistics objects are accessed first. One successful n_tup_ins case does not certify unrelated monitoring queries.

Develop the database judgment behind reliable monitoring

The durable skill in this exercise is learning to classify a surprising monitoring value before changing the system: collection, producer publication, reader retention, and ordinary MVCC visibility are separate evidence layers. PostgreSQL explicitly documents delayed cumulative-statistics publication, reader-side cache/snapshot/none semantics, statistics clearing, and transaction-isolation behavior; a reliable collector design makes those boundaries intentional rather than accidental.

For readers building that broader operational foundation, Refonte Learning’s Database Administrator Essentials program is listed as three months at 12–14 hours per week and covers database design, SQL optimization, backup and recovery, performance, security, cloud databases, migration and integration, disaster recovery, role-based access control, and monitoring and maintenance. The page describes practical projects, guidance, a potential internship, and Training and Internship certificates on successful completion.