Database engineer reviewing PostgreSQL snapshot handoffs, worker generation records, and parallel export results at a workstation.

PostgreSQL Exported Snapshots: How to Validate Parallel Exports

Thu, Nov 26, 2026

Two worker files can each be syntactically valid, internally ordered, and individually plausible while still being unsafe to publish together. One worker may have read revision 1, another revision 2; both may have imported valid PostgreSQL exported snapshots, but not the snapshot assigned to the same application generation. Conversely, two workers can genuinely share one MVCC view and still produce a broken artifact because their shard predicates overlap or leave a gap.

That is why a parallel extractor needs three independent proofs: visibility (which committed database view each worker read); provenance (whether the worker imported the token assigned to the intended generation); and coverage (whether the union of worker outputs contains every expected row exactly once). PostgreSQL supplies the snapshot synchronization mechanism, but artifact acceptance is an application-level protocol.

The qualification below uses one owned disposable database, one owner role, and exactly four database connections: coordinator C, workers A/B, and controlled writer W. Successful exporters and importers use REPEATABLE READ READ ONLY. The pinned runtime is PostgreSQL/psql 18.7, with CPython 3.13.3 deliberately selected for reproducibility rather than as a current-version recommendation. PostgreSQL 18.7 was released on November 12, 2026; the 18 documentation branch is used for contractual behavior, while runtime evidence must separately establish the actual 18.7 server and client versions.

Every case P01–P11 below is EXPECTED / NOT EXECUTED. No timings, PIDs, SQLSTATE values, hashes, or runtime observations are invented.

Define one coherent output generation

An extraction generation is an application concept, not a PostgreSQL object. In this protocol, generation G has exactly one coordinator-owned exporter transaction, one exported snapshot token supplied to all required workers, one immutable assignment plan, and complete worker acknowledgements. PostgreSQL documents pg_export_snapshot() as returning an opaque text identifier that must be passed outside the database; while its exporting transaction remains open, another transaction can import that snapshot and see the same pre-existing database state. The documentation also explicitly notes that locally uncommitted changes remain private to each transaction.

That distinction matters operationally. Snapshot agreement synchronizes the relevant stored-data MVCC view. It does not prove that two worker files belong to the same application job, that shard SQL is correct, or that every row appears exactly once.

A historic snapshot can also be perfectly valid without being the newest committed state. PostgreSQL’s parallel pg_dump workflow is useful context: parallel dump workers use synchronized snapshots so they operate against a coordinated database view. That demonstrates why parallel readers must coordinate; it does not imply that this custom extractor inherits pg_dump’s broader dump machinery or completeness safeguards.

The four publication decisions are deliberately different:

Decision

Meaning

ACCEPT

The intended generation, imports, outputs, multiplicities, completion evidence, and ownership cleanup all reconcile.

REPAIR

A deterministic configuration, ordering, routing, or shard-definition defect is understood and can be corrected before a clean qualification rerun.

RERUN

Evidence is inconclusive because of an environmental or harness failure; diagnose first, then execute a clean case rather than interpreting the failed attempt.

HOLD

Do not publish: the artifact is incomplete, mixed-generation, unexplained, or otherwise cannot currently satisfy the acceptance contract.

This fixture deliberately excludes backup/restore qualification, replication, production migration, connection pooling, RLS, sequence watermarks, notifications, advisory locks, concurrent DDL, volatile expressions, and COPY FREEZE. The nearby Refonte Learning article on COPY FREEZE and old-snapshot visibility tests a deliberately exceptional MVCC-loading behavior; the workflow here uses ordinary committed tables and ordinary extraction.

Pin the database and client boundary

The qualification contract begins with a literal environment manifest. Documentation branch numbers are insufficient evidence of the executable environment: the PostgreSQL 18.7 release notes identify the selected maintenance release and its November 12, 2026 release date, while psql exposes its own version separately.

Field

Required value

Server

PostgreSQL 18.7

server_version_num

180007

Client

psql 18.7

Coordinator runtime

CPython 3.13.3

Database

one owned disposable database

Role

one owner role for fixture and all four connections

Schema

snapshot_handoff

Connections

C, A, B, W only

Successful snapshot transactions

REPEATABLE READ READ ONLY

V1

(1,1,100),(2,1,200),(3,1,300),(4,1,400)

V2

(1,2,60),(2,2,200),(3,2,300),(4,2,440)

Correct A shard

id <= 2

Correct B shard

id > 2

The driver refuses a server-version or client-version mismatch rather than silently treating another PostgreSQL minor release as equivalent evidence. CPython 3.13.3 was released April 8, 2025 and is now historical; its use here is a reproducibility pin only. The Python subprocess documentation currently rendered under the 3.13 branch identifies itself as 3.13.18, not an exact 3.13.3 manual. It documents the stable Popen, pipe, argument-sequence, timeout, and return-code interfaces used below; that moving documentation page is therefore supporting API documentation, not evidence that Python 3.13.3 was executed.

The owned lab must also exclude other writers and concurrent DDL. W is the only controlled mutation source during a case. Resetting the schema happens only after every transaction and psql process from the preceding case has terminated.

Capture connection identity before BEGIN

Each worker’s endpoint, database, role, server version, backend PID, and relevant defaults are captured before the importing transaction begins. That metadata query must not accidentally become the first query inside the import transaction.

The required worker sequence is:

-- Worker A or B: metadata is collected before BEGIN.
SELECT json_build_object(
    'server_version', current_setting('server_version'),
    'server_version_num', current_setting('server_version_num'),
    'database', current_database(),
    'role', current_user,
    'backend_pid', pg_backend_pid(),
    'default_transaction_isolation',
        current_setting('default_transaction_isolation')
);

-- Now the importing transaction begins.
BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY;

-- This must be the next server statement.
SET TRANSACTION SNAPSHOT :'snapshot_id';

PostgreSQL requires snapshot import at the start of the transaction, before the first query or data-modification statement, and requires an importer to use REPEATABLE READ or SERIALIZABLE. If the importer is SERIALIZABLE, the exporter must also be SERIALIZABLE.

The psql spelling is significant. :'snapshot_id' safely interpolates a psql variable as an SQL string literal; writing ':snapshot_id' instead places the colon text inside an already quoted SQL literal and prevents interpolation. PostgreSQL’s psql documentation explicitly distinguishes those forms.

Every psql process starts with -X, which suppresses system and user startup files, and with ON_ERROR_STOP=on and verbose diagnostics. PostgreSQL documents -X as disabling psqlrc, ON_ERROR_STOP as stopping processing on errors, and psql exit statuses as separate from the server’s detailed error report. The snapshot token is supplied as one element in the Python Popen argument list using --set=snapshot_id=...; no shell is involved. Python recommends argument sequences for subprocess invocation and warns that undrained stdout/stderr pipes can block a child.

Build the shared fixture and external coordinator

The fixture is intentionally tiny because its oracle must remain independently auditable. The setup is committed before any case starts.

-- Actor C: fixture.sql
\set ON_ERROR_STOP on

BEGIN;

DROP SCHEMA IF EXISTS snapshot_handoff CASCADE;
CREATE SCHEMA snapshot_handoff AUTHORIZATION CURRENT_USER;

CREATE TABLE snapshot_handoff.accounts (
    id       integer PRIMARY KEY,
    revision integer NOT NULL,
    amount   integer NOT NULL
);

INSERT INTO snapshot_handoff.accounts(id, revision, amount)
VALUES
    (1, 1, 100),
    (2, 1, 200),
    (3, 1, 300),
    (4, 1, 400);

COMMIT;

W performs the only in-case mutation:

-- Actor W: V1 -> V2, one atomic transaction.
BEGIN;

UPDATE snapshot_handoff.accounts
SET revision = 2,
    amount = CASE id
        WHEN 1 THEN 60
        WHEN 4 THEN 440
        ELSE amount
    END;

COMMIT;

V1 and V2 deliberately share the same row count and total amount, four rows totaling 1,000. That prevents “count plus checksum-like sum” from becoming an accidental substitute for row-level reconciliation.

The Python coordinator below uses only the standard library. Each database actor is a persistent psql child process. Commands are framed with unambiguous client-side markers. stdout and stderr are drained concurrently to files and a queue, waits are bounded, EOF is explicit, and a missing frame terminator fails closed. Python’s subprocess documentation specifically cautions that waiting on a process with undrained pipe output can deadlock; continuous drain threads avoid that condition here.

The extractor uses ordinary COPY (SELECT ...) TO STDOUT. PostgreSQL documents that COPY TO can copy the results of a query and that STDOUT sends data over the client connection. Serialization is only the transport mechanism; it says nothing about snapshot provenance or shard completeness.

# coordinator.py
# Required runtime: CPython 3.13.3
# EXPECTED qualification harness; no execution is claimed by this article.

from future import annotations

import csv
import hashlib
import json
import os
import platform
import queue
import re
import subprocess
import sys
import threading
import time
from dataclasses import dataclass
from pathlib import Path

PSQL = os.environ.get("PSQL", "psql")
PGHOST = os.environ["PGHOST"]
PGPORT = os.environ.get("PGPORT", "5432")
PGDATABASE = os.environ["PGDATABASE"]
PGUSER = os.environ["PGUSER"]
ROOT = Path(os.environ.get("EVIDENCE_ROOT", "evidence"))
TIMEOUT = float(os.environ.get("CASE_TIMEOUT_SECONDS", "15"))

EXPECTED_PYTHON = "3.13.3"
EXPECTED_PSQL = "18.7"
EXPECTED_SERVER_NUM = "180007"

V1 = [(1, 1, 100), (2, 1, 200), (3, 1, 300), (4, 1, 400)]
V2 = [(1, 2, 60), (2, 2, 200), (3, 2, 300), (4, 2, 440)]

CORRECT_A = "id <= 2"
CORRECT_B = "id > 2"
BAD_B_P10 = "id >= 2 AND id < 4"

PROFILE_SQL = """
SELECT json_build_object(
 'server_version', current_setting('server_version'),
 'server_version_num', current_setting('server_version_num'),
 'database', current_database(),
 'role', current_user,
 'backend_pid', pg_backend_pid(),
 'default_transaction_isolation',
     current_setting('default_transaction_isolation')
);
"""

RESET_SQL = """
BEGIN;
DROP SCHEMA IF EXISTS snapshot_handoff CASCADE;
CREATE SCHEMA snapshot_handoff AUTHORIZATION CURRENT_USER;
CREATE TABLE snapshot_handoff.accounts (
 id integer PRIMARY KEY,
 revision integer NOT NULL,
 amount integer NOT NULL
);
INSERT INTO snapshot_handoff.accounts(id, revision, amount)
VALUES (1,1,100),(2,1,200),(3,1,300),(4,1,400);
COMMIT;
"""

WRITE_V2 = """
BEGIN;
UPDATE snapshot_handoff.accounts
SET revision = 2,
    amount = CASE id WHEN 1 THEN 60 WHEN 4 THEN 440 ELSE amount END;
COMMIT;
"""

@dataclass
class Result:
    ok: bool
    stdout: list[str]
    stderr: list[str]
    returncode: int | None

def sha256_text(s: str) -> str:
    return hashlib.sha256(s.encode("utf-8")).hexdigest()

def dump_json(path: Path, obj) -> None:
    path.write_text(json.dumps(obj, indent=2, sort_keys=True) + "\n",
                    encoding="utf-8")

class PsqlSession:
    def init(self, actor: str, case_dir: Path, snapshot: str | None = None):
        self.actor = actor
        self.case_dir = case_dir
        self.case_dir.mkdir(parents=True, exist_ok=True)
        self.events = queue.Queue()
        self.counter = 0

        args = [
            PSQL, "-X", "-qAt",
            "-v", "ON_ERROR_STOP=on",
            "-v", "VERBOSITY=verbose",
            "-P", "pager=off",
            "-h", PGHOST,
            "-p", PGPORT,
            "-d", PGDATABASE,
            "-U", PGUSER,
        ]
        if snapshot is not None:
            # Opaque token crosses the client boundary as one argv element.
            args += ["--set", f"snapshot_id={snapshot}"]

        self.args_redacted = args[:]  # no password is placed in argv
        self.stdout_path = case_dir / f"{actor}.stdout.log"
        self.stderr_path = case_dir / f"{actor}.stderr.log"
        self.stdout_file = self.stdout_path.open("w", encoding="utf-8")
        self.stderr_file = self.stderr_path.open("w", encoding="utf-8")

        env = os.environ.copy()
        env["PGAPPNAME"] = f"snapshot-qualification-{actor}"

        self.proc = subprocess.Popen(
            args,
            stdin=subprocess.PIPE,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True,
            encoding="utf-8",
            errors="replace",
            bufsize=1,
            shell=False,
            env=env,
        )

        assert self.proc.stdin and self.proc.stdout and self.proc.stderr

        self.threads = [
            threading.Thread(
                target=self._drain,
                args=("stdout", self.proc.stdout, self.stdout_file),
                daemon=True,
            ),
            threading.Thread(
                target=self._drain,
                args=("stderr", self.proc.stderr, self.stderr_file),
                daemon=True,
            ),
        ]
        for t in self.threads:
            t.start()

    def drain(self, streamname, stream, log_file):
        try:
            for line in stream:
                log_file.write(line)
                log_file.flush()
                self.events.put((stream_name, line.rstrip("\n")))
        finally:
            self.events.put((stream_name, None))

    def marker(self, label: str) -> str:
        self.counter += 1
        return f"@@{self.actor}:{self.counter}:{label}@@"

    def execute(self, sql: str, label: str, timeout: float = TIMEOUT) -> Result:
        marker = self.marker(label)
        if self.proc.poll() is not None:
            return Result(False, [], ["process already exited"], self.proc.returncode)

        assert self.proc.stdin
        self.proc.stdin.write(sql.rstrip() + "\n")
        self.proc.stdin.write(f"\\echo {marker}\n")
        self.proc.stdin.flush()

        out, err = [], []
        deadline = time.monotonic() + timeout
        stdout_eof = stderr_eof = False

        while time.monotonic() < deadline:
            try:
                stream, line = self.events.get(timeout=0.1)
            except queue.Empty:
                if self.proc.poll() is not None and stdout_eof and stderr_eof:
                    break
                continue

            if line is None:
                if stream == "stdout":
                    stdout_eof = True
                else:
                    stderr_eof = True
                continue

            if stream == "stdout":
                if line == marker:
                    return Result(True, out, err, self.proc.poll())
                out.append(line)
            else:
                err.append(line)

        if self.proc.poll() is None:
            self.proc.terminate()
            try:
                self.proc.wait(timeout=2)
            except subprocess.TimeoutExpired:
                self.proc.kill()
                self.proc.wait(timeout=2)

        return Result(False, out, err, self.proc.returncode)

    def profile(self) -> dict:
        r = self.execute(PROFILE_SQL, "PROFILE")
        if not r.ok:
            raise RuntimeError(f"{self.actor}: profile failed: {r.stderr}")
        values = [x for x in r.stdout if x.strip()]
        if len(values) != 1:
            raise RuntimeError(f"{self.actor}: ambiguous profile output: {values}")
        obj = json.loads(values[0])
        if obj["server_version_num"] != EXPECTED_SERVER_NUM:
            raise RuntimeError(
                f"{self.actor}: server_version_num "
                f"{obj['server_version_num']} != {EXPECTED_SERVER_NUM}"
            )
        return obj

    def import_rr(self) -> Result:
        return self.execute(
            """
BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY;
SET TRANSACTION SNAPSHOT :'snapshot_id';
""",
            "IMPORT_RR",
        )

    def extract(self, predicate: str, target: Path) -> list[tuple[int, int, int]]:
        sql = f"""
COPY (
 SELECT id, revision, amount
 FROM snapshot_handoff.accounts
 WHERE {predicate}
 ORDER BY id
) TO STDOUT WITH (FORMAT csv, HEADER true);
"""
        r = self.execute(sql, "COPY")
        if not r.ok:
            raise RuntimeError(f"{self.actor}: COPY failed: {r.stderr}")

        lines = [x for x in r.stdout if x.strip()]
        try:
            h = lines.index("id,revision,amount")
        except ValueError as exc:
            raise RuntimeError(f"{self.actor}: CSV header missing: {lines}") from exc

        payload = []
        copy_count = None
        for line in lines[h + 1:]:
            if re.fullmatch(r"COPY \d+", line):
                copy_count = int(line.split()[1])
                continue
            if not re.fullmatch(r"-?\d+,-?\d+,-?\d+", line):
                raise RuntimeError(
                    f"{self.actor}: unexpected framed COPY output: {line!r}"
                )
            payload.append(tuple(map(int, line.split(","))))

        if copy_count is not None and copy_count != len(payload):
            raise RuntimeError(
                f"{self.actor}: COPY tag {copy_count} != rows {len(payload)}"
            )

        target.parent.mkdir(parents=True, exist_ok=True)
        with target.open("w", newline="", encoding="utf-8") as f:
            w = csv.writer(f)
            w.writerow(["id", "revision", "amount"])
            w.writerows(payload)
        return payload

    def close(self):
        if self.proc.poll() is None:
            try:
                assert self.proc.stdin
                self.proc.stdin.write("ROLLBACK;\n\\q\n")
                self.proc.stdin.flush()
            except (BrokenPipeError, OSError):
                pass
            try:
                self.proc.wait(timeout=3)
            except subprocess.TimeoutExpired:
                self.proc.terminate()
                try:
                    self.proc.wait(timeout=2)
                except subprocess.TimeoutExpired:
                    self.proc.kill()
                    self.proc.wait(timeout=2)

        for t in self.threads:
            t.join(timeout=1)
        self.stdout_file.close()
        self.stderr_file.close()

def token_from(result: Result) -> str:
    if not result.ok:
        raise RuntimeError(f"snapshot export failed: {result.stderr}")
    vals = [x for x in result.stdout if x.strip()]
    if len(vals) != 1:
        raise RuntimeError(f"ambiguous snapshot token output: {vals}")
    return vals[0]

def export_rr(c: PsqlSession) -> str:
    return token_from(c.execute(
        """
BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY;
SELECT pg_export_snapshot();
""",
        "EXPORT_RR",
    ))

def writer_to_v2(w: PsqlSession):
    r = w.execute(WRITE_V2, "WRITE_V2_COMMIT")
    if not r.ok:
        raise RuntimeError(f"W commit failed: {r.stderr}")

def fresh_v2(w: PsqlSession) -> list[str]:
    r = w.execute(
        """
SELECT id || ',' || revision || ',' || amount
FROM snapshot_handoff.accounts
ORDER BY id;
""",
        "FRESH_V2",
    )
    if not r.ok:
        raise RuntimeError(f"W fresh read failed: {r.stderr}")
    return r.stdout

def persist_rows(case_dir: Path, a_rows, b_rows):
    rows = list(a_rows) + list(b_rows)
    p = case_dir / "rows" / "combined.csv"
    p.parent.mkdir(parents=True, exist_ok=True)
    with p.open("w", newline="", encoding="utf-8") as f:
        w = csv.writer(f)
        w.writerow(["id", "revision", "amount"])
        w.writerows(rows)
    dump_json(case_dir / "combined-summary.json", {
        "ordered_rows": rows,
        "row_count": len(rows),
        "amount_total": sum(r[2] for r in rows),
    })

class Case:
    def init(self, run_id: str, case_id: str):
        self.case_id = case_id
        self.dir = ROOT / run_id / case_id
        self.dir.mkdir(parents=True, exist_ok=True)
        self.sessions: list[PsqlSession] = []
        self.c = self.new("C")
        self.c.profile()
        rr = self.c.execute(RESET_SQL, "RESET_V1")
        if not rr.ok:
            raise RuntimeError(f"{case_id}: reset failed: {rr.stderr}")

    def new(self, actor: str, snapshot: str | None = None) -> PsqlSession:
        s = PsqlSession(actor, self.dir, snapshot)
        self.sessions.append(s)
        return s

    def close(self):
        for s in reversed(self.sessions):
            s.close()

def ensure_runtime(run_dir: Path):
    if platform.python_version() != EXPECTED_PYTHON:
        raise RuntimeError(
            f"Python {platform.python_version()} != required {EXPECTED_PYTHON}"
        )
    r = subprocess.run(
        [PSQL, "--version"],
        text=True,
        capture_output=True,
        shell=False,
        timeout=5,
        check=False,
    )
    if r.returncode != 0 or EXPECTED_PSQL not in r.stdout:
        raise RuntimeError(
            f"psql version mismatch: rc={r.returncode}, out={r.stdout!r}"
        )
    dump_json(run_dir / "runtime.json", {
        "python": platform.python_version(),
        "psql_version_stdout": r.stdout.strip(),
        "expected_server_version_num": EXPECTED_SERVER_NUM,
        "host": PGHOST,
        "port": PGPORT,
        "database": PGDATABASE,
        "role": PGUSER,
    })

def p01(run):
    x = Case(run, "P01")
    try:
        a = x.new("A"); a.profile()
        w = x.new("W"); w.profile()
        b = x.new("B")
        if not a.execute(
            "BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY;",
            "A_BEGIN"
        ).ok: raise RuntimeError("A begin failed")
        ar = a.extract(CORRECT_A, x.dir/"rows"/"A.csv")
        a.execute("COMMIT;", "A_COMMIT")
        writer_to_v2(w)
        b.profile()
        if not b.execute(
            "BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY;",
            "B_BEGIN"
        ).ok: raise RuntimeError("B begin failed")
        br = b.extract(CORRECT_B, x.dir/"rows"/"B.csv")
        b.execute("COMMIT;", "B_COMMIT")
        persist_rows(x.dir, ar, br)
    finally:
        x.close()

def p02(run):
    x = Case(run, "P02")
    try:
        s0 = export_rr(x.c)
        a = x.new("A", s0); a.profile()
        b = x.new("B", s0); b.profile()
        w = x.new("W"); w.profile()
        if not a.import_rr().ok or not b.import_rr().ok:
            raise RuntimeError("worker import failed")
        x.c.execute("COMMIT;", "C_RELEASE")
        writer_to_v2(w)
        ar = a.extract(CORRECT_A, x.dir/"rows"/"A.csv")
        br = b.extract(CORRECT_B, x.dir/"rows"/"B.csv")
        persist_rows(x.dir, ar, br)
        dump_json(x.dir/"W-fresh.json", {"rows": fresh_v2(w)})
    finally:
        x.close()

def p03(run):
    x = Case(run, "P03")
    try:
        s0 = export_rr(x.c)
        a = x.new("A", s0); a.profile()
        w = x.new("W"); w.profile()
        if not a.import_rr().ok: raise RuntimeError("A import failed")
        writer_to_v2(w)
        b = x.new("B", s0); b.profile()
        if not b.import_rr().ok: raise RuntimeError("B late import failed")
        x.c.execute("COMMIT;", "C_COMMIT")
        ar = a.extract(CORRECT_A, x.dir/"rows"/"A.csv")
        br = b.extract(CORRECT_B, x.dir/"rows"/"B.csv")
        persist_rows(x.dir, ar, br)
        dump_json(x.dir/"W-fresh.json", {"rows": fresh_v2(w)})
    finally:
        x.close()

def p04(run):
    x = Case(run, "P04")
    try:
        s0 = export_rr(x.c)
        a = x.new("A", s0); a.profile()
        w = x.new("W"); w.profile()
        if not a.import_rr().ok: raise RuntimeError("A import failed")
        writer_to_v2(w)
        x.c.execute("COMMIT;", "C_COMMIT")
        b = x.new("B", s0); b.profile()
        r = b.import_rr()
        dump_json(x.dir/"B-import-observation.json", {
            "marker_reached": r.ok,
            "returncode": r.returncode,
            "stderr": r.stderr,
        })
        ar = a.extract(CORRECT_A, x.dir/"rows"/"A.csv")
        dump_json(x.dir/"A-partial.json", {"ordered_rows": ar})
    finally:
        x.close()

def p05(run):
    x = Case(run, "P05")
    try:
        # No explicit BEGIN: token dies when this autocommit statement ends.
        s0 = token_from(x.c.execute(
            "SELECT pg_export_snapshot();", "AUTOCOMMIT_EXPORT"
        ))
        a = x.new("A"); a.profile()
        w = x.new("W"); w.profile()
        b = x.new("B", s0); b.profile()
        r = b.import_rr()
        dump_json(x.dir/"B-import-observation.json", {
            "marker_reached": r.ok,
            "returncode": r.returncode,
            "stderr": r.stderr,
        })
    finally:
        x.close()

def p06(run):
    x = Case(run, "P06")
    try:
        s0 = export_rr(x.c)
        a = x.new("A"); a.profile()
        w = x.new("W"); w.profile()
        b = x.new("B", s0); b.profile()
        r = b.execute(
            """
BEGIN ISOLATION LEVEL READ COMMITTED READ ONLY;
SET TRANSACTION SNAPSHOT :'snapshot_id';
""",
            "READ_COMMITTED_IMPORT",
        )
        dump_json(x.dir/"B-import-observation.json", vars(r))
    finally:
        x.close()

def p07(run):
    x = Case(run, "P07")
    try:
        s0 = export_rr(x.c)
        a = x.new("A"); a.profile()
        w = x.new("W"); w.profile()
        b = x.new("B", s0); b.profile()
        r = b.execute(
            """
BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY;
SELECT pg_backend_pid();
SET TRANSACTION SNAPSHOT :'snapshot_id';
""",
            "QUERY_BEFORE_IMPORT",
        )
        dump_json(x.dir/"B-import-observation.json", vars(r))
    finally:
        x.close()

def p08(run):
    x = Case(run, "P08")
    try:
        s0 = export_rr(x.c)  # exporter is RR, not SERIALIZABLE
        a = x.new("A"); a.profile()
        w = x.new("W"); w.profile()
        b = x.new("B", s0); b.profile()
        r = b.execute(
            """
BEGIN ISOLATION LEVEL SERIALIZABLE READ ONLY;
SET TRANSACTION SNAPSHOT :'snapshot_id';
""",
            "SERIALIZABLE_IMPORT_FROM_RR",
        )
        dump_json(x.dir/"B-import-observation.json", vars(r))
    finally:
        x.close()

def p09(run):
    x = Case(run, "P09")
    try:
        s0 = export_rr(x.c)
        a = x.new("A", s0); a.profile()
        if not a.import_rr().ok: raise RuntimeError("A import S0 failed")
        w = x.new("W"); w.profile()
        writer_to_v2(w)
        x.c.execute("COMMIT;", "END_S0")
        s1 = export_rr(x.c)
        b = x.new("B", s1); b.profile()
        if not b.import_rr().ok: raise RuntimeError("B import S1 failed")
        x.c.execute("COMMIT;", "END_S1")
        ar = a.extract(CORRECT_A, x.dir/"rows"/"A.csv")
        br = b.extract(CORRECT_B, x.dir/"rows"/"B.csv")
        persist_rows(x.dir, ar, br)
        dump_json(x.dir/"generation-routing.json", {
            "job_label": "old-generation-label",
            "A_supplied_token": s0,
            "B_supplied_token": s1,
            "token_equal": s0 == s1,
        })
    finally:
        x.close()

def p10(run):
    x = Case(run, "P10")
    try:
        s0 = export_rr(x.c)
        a = x.new("A", s0); a.profile()
        b = x.new("B", s0); b.profile()
        w = x.new("W"); w.profile()
        if not a.import_rr().ok or not b.import_rr().ok:
            raise RuntimeError("worker import failed")
        x.c.execute("COMMIT;", "C_RELEASE")
        ar = a.extract(CORRECT_A, x.dir/"rows"/"A.csv")
        br = b.extract(BAD_B_P10, x.dir/"rows"/"B.csv")
        persist_rows(x.dir, ar, br)
    finally:
        x.close()

def p11(run):
    x = Case(run, "P11")
    try:
        w = x.new("W"); w.profile()
        writer_to_v2(w)  # fresh committed V2 starting state
        s1 = export_rr(x.c)
        a = x.new("A", s1); a.profile()
        b = x.new("B", s1); b.profile()
        if not a.import_rr().ok or not b.import_rr().ok:
            raise RuntimeError("fresh-generation import failed")
        x.c.execute("COMMIT;", "C_RELEASE")
        ar = a.extract(CORRECT_A, x.dir/"rows"/"A.csv")
        br = b.extract(CORRECT_B, x.dir/"rows"/"B.csv")
        persist_rows(x.dir, ar, br)
    finally:
        x.close()

CASES = {
    "P01": p01, "P02": p02, "P03": p03, "P04": p04,
    "P05": p05, "P06": p06, "P07": p07, "P08": p08,
    "P09": p09, "P10": p10, "P11": p11,
}

def main():
    if len(sys.argv) != 3:
        raise SystemExit("usage: coordinator.py RUN_ID P01|...|P11|ALL")
    run_id, requested = sys.argv[1], sys.argv[2]
    run_dir = ROOT / run_id
    run_dir.mkdir(parents=True, exist_ok=False)
    ensure_runtime(run_dir)

    selected = list(CASES) if requested == "ALL" else [requested]
    for case_id in selected:
        CASES[case_id](run_id)

if name == "__main__":
    main()

The coordinator host launches the harness directly, again without shell interpolation:

[coordinator host]
python3 coordinator.py qualification-2026-11-26 ALL

The source above deliberately does not fabricate a “PASS” result. Actual execution must persist the interpreter version, psql version, server profile, exact command material, raw streams, process statuses, and generated files.

Preserve four rows as an independent oracle

The immutable logical oracle is authored separately from extraction SQL:

{
  "V1": [[1,1,100],[2,1,200],[3,1,300],[4,1,400]],
  "V2": [[1,2,60],[2,2,200],[3,2,300],[4,2,440]],
  "correct_assignments": {
    "A": [1,2],
    "B": [3,4]
  }
}

The controlled update yields V2 (1,2,60),(2,2,200),(3,2,300),(4,2,440). Both V1 and V2 contain four rows and total 1,000. No expected row is discovered by rerunning a production/extraction WHERE clause.

The complete qualification index is:

ID

Ordered intervention

Independent expected outcome and artifact decision

P01

A reads ordinary RR V1 shard; W commits V2; B independently begins RR afterward; no import.

EXPECTED / NOT EXECUTED: (1,1,100),(2,1,200),(3,2,300),(4,2,440); count 4, sum 1,040. Diagnostic matches; REPAIR synchronization and reject artifact.

P02

C exports S0/V1; A/B import; W commits V2; workers extract afterward.

EXPECTED / NOT EXECUTED: literal V1 exactly once; W fresh read V2. Eligible for ACCEPT after all gates.

P03

C exports S0; A imports; W commits V2; B only then begins/imports S0 while C stays live.

EXPECTED / NOT EXECUTED: B still V1; combined literal V1. Positive handoff control.

P04

C exports S0; A imports; W commits; C commits; B attempts S0; A later reads.

EXPECTED / NOT EXECUTED: B import rejected; A retains V1 IDs 1/2. HOLD incomplete generation.

P05

C exports without explicit BEGIN; autocommit statement ends; B imports returned token.

EXPECTED / NOT EXECUTED: import rejected. REPAIR exporter lifetime.

P06

Live C/S0; B starts READ COMMITTED READ ONLY and imports.

EXPECTED / NOT EXECUTED: import rejected. REPAIR importer isolation.

P07

Live C/S0; B begins RR RO, executes SELECT pg_backend_pid(), then imports.

EXPECTED / NOT EXECUTED: import rejected. REPAIR telemetry ordering.

P08

C exports from RR RO; B begins SERIALIZABLE RO and imports.

EXPECTED / NOT EXECUTED: import rejected because exporter is not SERIALIZABLE. REPAIR compatibility.

P09

A imports S0/V1; W commits V2; C starts fresh exporter S1/V2; B receives S1 under old job label.

EXPECTED / NOT EXECUTED: imports succeed but mixed V1/V2 gives count 4, sum 1,040. HOLD, then REPAIR routing/provenance.

P10

Both import S0/V1; A uses id<=2; B wrongly uses id>=2 AND id<4.

EXPECTED / NOT EXECUTED: (1,1,100),(2,1,200),(2,1,200),(3,1,300); duplicate 2, missing 4; count 4, sum 800. REPAIR shards; reject artifact.

P11

Archive rejected material; terminate owned old transactions; create fresh V2 generation with correct shards.

EXPECTED / NOT EXECUTED: literal V2 exactly once; ACCEPT only the new generation after all gates.

Demonstrate why independent readers disagree

P01 is the control showing why “both workers used Repeatable Read” is not enough. PostgreSQL’s Repeatable Read view is established relative to transaction/query timing; independent transactions do not thereby acquire one shared snapshot. PostgreSQL’s snapshot synchronization documentation expressly motivates exported snapshots with the possibility that a third transaction commits between independently started readers.

The required barriers are:

Step

Actor

Ordered action

1

A

BEGIN REPEATABLE READ READ ONLY.

2

A

Read IDs 1 and 2: V1.

3

W

UPDATE all rows to V2.

4

W

COMMIT acknowledged.

5

B

BEGIN REPEATABLE READ READ ONLY.

6

B

Read IDs 3 and 4: V2.

The literal combined diagnostic is:

(1,1,100)
(2,1,200)
(3,2,300)
(4,2,440)
count = 4
amount total = 1040

Each worker may be internally coherent. The combined file is still not an accepted generation.

This is also why the neighboring Refonte Learning discussion of statement and transaction read-view boundaries remains a distinct background topic. That article concerns a single SQL Server reader’s isolation semantics; P01 is only the preliminary failure mode for a PostgreSQL cross-session handoff protocol.

Establish the normal shared-snapshot handshake

P02 establishes the normal protocol.

-- C
BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY;
SELECT pg_export_snapshot();
-- application records opaque token S0

-- A, token supplied through psql argv
BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY;
SET TRANSACTION SNAPSHOT :'snapshot_id';

-- B, same supplied token S0
BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY;
SET TRANSACTION SNAPSHOT :'snapshot_id';

PostgreSQL defines exported snapshot identifiers as text values passed outside the database and importable while the exporting transaction remains open. The protocol records the supplied token, not merely “import succeeded.”

After A and B acknowledge successful import, W commits V2. A and B then extract their shards and must still produce literal V1:

A: (1,1,100),(2,1,200)
B: (3,1,300),(4,1,400)

W’s subsequent fresh statement, outside its completed update transaction, must independently confirm:

(1,2,60),(2,2,200),(3,2,300),(4,2,440)

That is the useful contrast: old imported view in A/B, fresh committed V2 in W.

The per-worker record must include generation ID, token supplied, query digest, shard assignment identity, profile, successful import acknowledgement, extraction completion, process state, and row-file digest. Token possession alone is not enough.

Acknowledge import before releasing the exporter

Our policy requires C to remain inside the exporting transaction until every required worker has successfully executed SET TRANSACTION SNAPSHOT. PostgreSQL says the snapshot remains available for import only until the exporter transaction ends.

After all required imports succeed, C may commit under this protocol; it does not have to remain open until every worker finishes extraction. That conclusion is a documented-contract derivation: the import-availability rule concerns future import, while Repeatable Read preserves the importing worker’s established view for its transaction. P04 separately tests that distinction.

Operationally:

Phase

Required action

Export

C exports S0.

Import and acknowledge

A imports S0 and acknowledges import. B imports S0 and acknowledges import.

Confirm the barrier

All required imports are acknowledged.

Release the exporter

C may end the exporting transaction.

Continue extraction

Workers continue extraction.

P02 is necessary but not the strongest positive control. If V1 simply stayed unchanged, two unrelated snapshots could produce identical rows. P03 deliberately introduces a committed boundary before B imports.

Import an old view after the writer commits

P03 makes the handoff discriminating.

The ordering is:

  1. C BEGIN RR READ ONLY.

  2. C exports S0 while fixture is V1.

  3. A BEGIN RR READ ONLY; A imports S0 successfully.

  4. W updates V1 -> V2 and receives COMMIT completion.

  5. Only now is B profiled.

  6. B BEGIN RR READ ONLY.

  7. B immediately imports S0 while C is still open.

  8. B extracts IDs 3,4 and is expected to obtain V1.

  9. W's fresh state is expected to be V2.

The key event is step 7, not a wall-clock timestamp. PostgreSQL documents both halves of the reasoning: an exported snapshot can be imported while its exporter remains open, and SET TRANSACTION SNAPSHOT must occur before the importing transaction’s first query/data modification. Repeatable Read then retains its database view rather than adopting W’s later commit.

Therefore the expected combined rows remain:

(1,1,100)
(2,1,200)
(3,1,300)
(4,1,400)

while W’s fresh observation is V2.

This is stronger evidence than merely seeing V1 twice: B’s importing transaction did not even begin until after the controlled V2 commit had completed. A successful old-view import is what connects B’s visibility to S0 rather than to coincidental timing.

End the exporter between worker imports

P04 separates importability from retained visibility.

C exports S0; A imports it. W commits V2. C then commits before B imports.

According to PostgreSQL, S0 is no longer available for new imports once C’s exporting transaction ends. B’s attempted import is therefore expected to fail. That failure must be captured as a failure at SET TRANSACTION SNAPSHOT, with raw server diagnostics retained.

A is different. A already imported S0. The expected A read after C ends is still:

(1,1,100)
(2,1,200)

Treating A as invalid merely because C later committed would conflate token import lifetime with an already established transaction view. The latter expectation follows from combining PostgreSQL’s export/import contract with Repeatable Read’s retained-view semantics.

Artifact acceptance is nevertheless HOLD. A valid partial shard cannot turn a generation with a missing required B shard into a publishable artifact. Import success belongs to the worker; completeness belongs to the generation.

Reject invalid import lifecycles

P05–P08 are negative controls. Each starts from a fresh disposable fixture after every process and owned transaction from the preceding case has ended.

P05 distinguishes a connected client from a live exporting transaction:

-- C: no explicit BEGIN
SELECT pg_export_snapshot();
-- statement completes; autocommit transaction ends

-- B:
BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY;
SET TRANSACTION SNAPSHOT :'snapshot_id';
-- EXPECTED / NOT EXECUTED: semantic rejection

The psql process can remain alive while the transaction that created the token is gone. PostgreSQL defines import availability in terms of the exporting transaction, not TCP connection lifetime.

P06 tests unsupported importer isolation:

-- C remains live with S0.

-- B:
BEGIN ISOLATION LEVEL READ COMMITTED READ ONLY;
SET TRANSACTION SNAPSHOT :'snapshot_id';
-- EXPECTED / NOT EXECUTED: semantic rejection

PostgreSQL requires snapshot-importing transactions to be REPEATABLE READ or SERIALIZABLE; READ COMMITTED would otherwise take snapshots per command.

P07 tests ordering:

-- B:
BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY;
SELECT pg_backend_pid();
SET TRANSACTION SNAPSHOT :'snapshot_id';
-- EXPECTED / NOT EXECUTED: semantic rejection

The telemetry query looks harmless, but it is still the transaction’s first query. PostgreSQL explicitly requires SET TRANSACTION SNAPSHOT before the first query or data-modification statement. This is why connection identity is captured before BEGIN, not after it.

P08 tests isolation compatibility:

-- C:
BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY;
SELECT pg_export_snapshot();

-- B:
BEGIN ISOLATION LEVEL SERIALIZABLE READ ONLY;
SET TRANSACTION SNAPSHOT :'snapshot_id';
-- EXPECTED / NOT EXECUTED: semantic rejection

If the importer is SERIALIZABLE, PostgreSQL requires the exporting transaction to be SERIALIZABLE as well. This article stops at that compatibility boundary; it does not expand into SERIALIZABLE write-conflict retry guidance.

Fail at the import statement, not at a later query

A negative control passes only when the intended semantic rejection occurs at SET TRANSACTION SNAPSHOT.

The evidence record needs:

{
  "case": "P07",
  "expected": "snapshot import rejected because a query preceded import",
  "execution_status": "EXPECTED / NOT EXECUTED",
  "required_runtime_evidence": [
    "exact submitted SQL",
    "verbose server diagnostic",
    "actual SQLSTATE from runtime output",
    "raw stdout",
    "raw stderr",
    "psql return code",
    "cleanup outcome"
  ]
}

No numeric SQLSTATE is hardcoded here. At runtime, psql’s verbose error mode must preserve the SQLSTATE actually emitted by PostgreSQL. PostgreSQL documents both the VERBOSITY control and psql’s distinct process exit statuses.

A syntax error, authentication failure, dead connection, timeout, or missing relation does not qualify as P05–P08’s expected semantic rejection. Such a case is RERUN after diagnosis, not a successful negative test.

A marker is likewise insufficient by itself. The harness requires the command marker, raw logs, and process-status accounting together. ON_ERROR_STOP prevents a failed command from silently flowing into later framed commands, but the reviewer still examines the actual server diagnostic.

Detect a valid token from the wrong generation

P09 demonstrates the most dangerous false positive in this protocol: both imports can succeed.

The sequence is:

S0 / generation G0:
  C exports S0 at V1
  A imports S0 successfully

W:
  commits V2

C:
  ends S0 exporter transaction
  begins a fresh RR transaction
  exports S1 at V2

routing defect:
  B receives S1 but is labelled as belonging to G0
  B imports S1 successfully

The expected output becomes:

A/G0: (1,1,100),(2,1,200)
B/misrouted-S1: (3,2,300),(4,2,440)
combined count = 4
combined amount = 1040

No PostgreSQL rule is violated by either successful import. The failure is application provenance.

The protocol therefore records the exact token supplied to each worker and rejects a generation whose required workers did not receive its declared token.

There is an important qualification. PostgreSQL says one transaction can export more than one snapshot identifier; in Repeatable Read and higher, those exports refer to the same transaction snapshot. Token inequality alone therefore does not universally prove different MVCC views. P09 deliberately avoids that inference: S1 comes from a fresh exporter transaction after W’s committed V2 update, and row revisions independently prove that B’s view differs from A’s.

Similarly, coordinator backend PID is not a generation identifier. One persistent C process can run several transactions on the same backend. Application generation identity must survive that reuse explicitly.

Reconcile partition coverage independently

P10 makes all snapshot evidence correct and the artifact wrong.

Both workers import S0/V1 successfully. A receives the intended predicate:

WHERE id <= 2

B is deliberately misconfigured:

WHERE id >= 2 AND id < 4

The output is therefore expected to be:

(1,1,100)
(2,1,200)
(2,1,200)
(3,1,300)

There are still four physical rows. A simplistic row-count check passes. Snapshot provenance passes. Every emitted row belongs to V1. Yet ID 2 occurs twice and ID 4 never occurs.

The immutable assignment manifest must therefore be external to worker output:

{
  "generation": "G0",
  "assignments": {
    "A": {"ids": [1, 2]},
    "B": {"ids": [3, 4]}
  },
  "required_columns": ["id", "revision", "amount"]
}

The principle is the same boundary illustrated by Refonte Learning’s separate discussion of independent partition-completeness checks: an observation cannot prove the existence of a unit that never arrived if the expected population is derived from the observation itself. Here the expected IDs cannot be discovered from the worker files being checked.

Never “repair” P10 by silently deduplicating the combined file. That would hide both the overlap and the missing ID, changing evidence rather than fixing the shard contract.

Check membership and multiplicity separately

The checker is intentionally independent from coordinator.py. It contains literal expected tuples and does not import worker predicates.

# check_generation.py
# Independent standard-library checker.

from future import annotations

import argparse
import csv
import json
from collections import Counter
from pathlib import Path

V1 = [
    (1, 1, 100),
    (2, 1, 200),
    (3, 1, 300),
    (4, 1, 400),
]

V2 = [
    (1, 2, 60),
    (2, 2, 200),
    (3, 2, 300),
    (4, 2, 440),
]

DIAGNOSTIC_EXPECTED = {
    "P01": [
        (1,1,100),(2,1,200),(3,2,300),(4,2,440)
    ],
    "P02": V1,
    "P03": V1,
    "P09": [
        (1,1,100),(2,1,200),(3,2,300),(4,2,440)
    ],
    "P10": [
        (1,1,100),(2,1,200),(2,1,200),(3,1,300)
    ],
    "P11": V2,
}

ACCEPTANCE_TARGET = {
    "P02": V1,
    "P03": V1,
    "P09": V1,   # old-generation label claims V1; mixed rows fail
    "P10": V1,   # same-view but bad membership fails
    "P11": V2,
}

def read_csv(path: Path):
    with path.open(newline="", encoding="utf-8") as f:
        r = csv.DictReader(f)
        if r.fieldnames != ["id", "revision", "amount"]:
            raise ValueError(
                f"{path}: columns {r.fieldnames!r} != required order"
            )
        return [
            (int(row["id"]), int(row["revision"]), int(row["amount"]))
            for row in r
        ]

def compare(actual, expected):
    actual_ids = Counter(r[0] for r in actual)
    expected_ids = Counter(r[0] for r in expected)

    expected_by_id = {r[0]: r for r in expected}
    actual_by_id = {}
    for row in actual:
        actual_by_id.setdefault(row[0], []).append(row)

    missing = sorted((expected_ids - actual_ids).elements())
    extra = sorted((actual_ids - expected_ids).elements())
    duplicate_ids = {
        k: v for k, v in sorted(actual_ids.items()) if v > 1
    }

    value_differences = {}
    for id_ in sorted(set(actual_ids) & set(expected_ids)):
        rows = actual_by_id[id_]
        if len(rows) == 1 and rows[0] != expected_by_id[id_]:
            value_differences[str(id_)] = {
                "expected": expected_by_id[id_],
                "actual": rows[0],
            }

    return {
        "ordered_exact_match": actual == expected,
        "row_count": len(actual),
        "expected_row_count": len(expected),
        "id_multiplicity": dict(sorted(actual_ids.items())),
        "expected_id_multiplicity": dict(sorted(expected_ids.items())),
        "missing_ids": missing,
        "extra_ids": extra,
        "duplicate_ids": duplicate_ids,
        "value_differences": value_differences,
        "amount_total": sum(r[2] for r in actual),
        "expected_amount_total": sum(r[2] for r in expected),
    }

def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--case", required=True)
    ap.add_argument("--combined", type=Path, required=True)
    args = ap.parse_args()

    actual = read_csv(args.combined)

    diagnostic = DIAGNOSTIC_EXPECTED.get(args.case)
    target = ACCEPTANCE_TARGET.get(args.case)

    result = {
        "case": args.case,
        "actual_rows": actual,
        "diagnostic": (
            compare(actual, diagnostic) if diagnostic is not None else None
        ),
        "acceptance": (
            compare(actual, target) if target is not None else None
        ),
    }

    if result["acceptance"] is None:
        result["artifact_acceptance"] = "NOT_APPLICABLE_OR_INCOMPLETE"
    elif result["acceptance"]["ordered_exact_match"]:
        result["artifact_acceptance"] = "ROW_ORACLE_PASS"
    else:
        result["artifact_acceptance"] = "ROW_ORACLE_FAIL"

    print(json.dumps(result, indent=2, sort_keys=True))

if name == "__main__":
    main()

Run it against the persisted artifact:

[reviewer host]
python3 check_generation.py \
  --case P10 \
  --combined evidence/<run>/P10/rows/combined.csv

The algorithm checks ordered tuple identity, count, per-ID multiplicity, missing IDs, extra IDs, duplicate IDs, differing row values, and totals. A set comparison alone would discard multiplicity; count four alone misses P10; total 1,000 alone cannot distinguish V1 from V2.

Preserve the complete evidence bundle

A qualification run should be reconstructable without relying on terminal history or human memory. The evidence tree can look like this:

evidence/
  qualification-2026-11-26/
    runtime.json
    P01/
      C.stdout.log
      C.stderr.log
      A.stdout.log
      A.stderr.log
      B.stdout.log
      B.stderr.log
      W.stdout.log
      W.stderr.log
      rows/
        A.csv
        B.csv
        combined.csv
      combined-summary.json
      checker.json
      environment.json
      generation.json
      phase-events.jsonl
      shard-plan.json
      query-digests.json
      cleanup.json
    P02/
      ...
    ...
    P11/
      ...

The real execution should retain endpoint/database/role identity, actual backend and OS process IDs, client/server/runtime versions, command text or exact query digests, immutable shard plan, generation IDs, supplied tokens, successful-import acknowledgements, writer commit acknowledgement, raw stdout/stderr, errors, row files, checker output, and cleanup results.

Digests belong to execution time. For example:

digest = hashlib.sha256(sql_text.encode("utf-8")).hexdigest()

The article intentionally prints no made-up digest.

Credentials should be redacted, but provenance should not. A token may itself deserve restricted handling because it is an operational database identifier; if evidence policy redacts it from broad logs, preserve a controlled exact-value record or cryptographic digest sufficient for the reviewer’s provenance procedure.

A successful COPY proves that serialization completed, not that the rows came from the intended generation or covered every assigned ID. PostgreSQL’s COPY contract is about data transfer, not this application acceptance protocol. Likewise, why an ID checkpoint does not prove completeness is a separate failure mode: this qualification instead reconciles one closed four-row fixture against an independent manifest.

Recover without combining generations

P11 qualifies the chosen recovery policy: reject the old generation as a unit, archive its evidence, terminate only owned transactions/processes, and restart all required shards under a new generation.

That is an application policy, not a claim that PostgreSQL technically forbids every conceivable partial reuse strategy.

The safe sequence for this qualification is:

  1. Mark old generation REJECTED/HOLD.

  2. Preserve A/B files and all logs as diagnostic evidence.

  3. End only the old coordinator/worker transactions owned by this run.

  4. Confirm all four psql processes have terminal statuses.

  5. Reset or prepare the disposable fixture only after old transactions end.

  6. Establish committed V2 as the new starting state.

  7. Allocate a new application generation ID.

  8. C starts a fresh RR RO exporter transaction.

  9. C exports a new token.

  10. A/B start fresh importing transactions and import that token.

  11. C releases only after all required import acknowledgements.

  12. A/B extract the correct immutable assignments.

  13. Independently reconcile literal V2.

  14. ACCEPT only the new generation if every gate passes.

A database rollback cannot erase files already written by a client. Old output directories therefore remain quarantined by generation rather than being overwritten.

The key anti-pattern is:

rejected G0/A.csv
+
new G1/B.csv
=
"complete" directory

That reconstruction may happen to contain IDs 1–4 but no longer represents one qualified generation. P09 already shows why that is unsafe.

Start a fresh generation without reusing old parts

P11 begins from committed V2. C then starts a fresh exporter transaction and exports a new token. A and B import that token, receive the correct assignments, and the independent checker expects:

(1,2,60)
(2,2,200)
(3,2,300)
(4,2,440)

The expected count is four, every ID has multiplicity one, every revision is two, and the amount total is 1,000.

The new generation must have a new generation identity, new exporter transaction, new token record, new worker-import records, new row files, new digests, and new cleanup record. The old files remain rejected evidence.

It is conceivable that a surviving imported reader could participate in some other deliberately designed protocol. That is outside this qualification. The restart-all rule is chosen because it makes generation ownership and acceptance auditable, not because PostgreSQL makes every alternative impossible.

Terminal cleanup is part of both success and failure. C/A/B/W transactions must be committed, rolled back, or terminated according to the case; psql child processes must have final return-code evidence; only explicitly owned disposable objects may then be dropped or recreated.

Decide ACCEPT, REPAIR, RERUN or HOLD

The final gate separates a database mechanism from an operational publication decision.

Condition

Decision

Owner

Required action

Correct environment; intended token/generation; ordered imports succeed; all workers complete; literal tuples and multiplicity reconcile; cleanup accounted for

ACCEPT

Coordinator + extraction owner + reviewer

Publish only that generation

Exporter lifetime, importer mode, telemetry ordering, token routing, or shard predicate is deterministically wrong

REPAIR

Coordinator for handoff/routing; extraction owner for SQL/assignment

Correct configuration/protocol, archive old evidence

Authentication, timeout, dropped connection, malformed harness, missing logs, or other evidence failure prevents semantic interpretation

RERUN

Reliability/coordinator owner

Diagnose first; recreate disposable case and rerun cleanly

Missing shard, mixed generation, unexplained contradiction, failed provenance, or incomplete evidence

HOLD

Reviewer/release owner

Prevent publication until resolved

The coordinator owns exporter lifetime, token handoff, generation routing, phase barriers, and process accounting. The extraction owner owns worker SQL, output framing, immutable assignments, and data-file production. The reviewer owns the independent manifest, checker execution, negative-control interpretation, and the final publication decision.

The case ledger must account for P01 through P11 exactly once per qualification run, with every required phase represented. A manifest containing eleven names is not itself evidence that the phases happened.

Expected ownership and disposition are:

Case

Expected qualification disposition

P01

REPAIR synchronization; reject artifact

P02

ACCEPT-eligible after all gates

P03

ACCEPT-eligible positive control

P04

HOLD incomplete generation

P05

REPAIR exporter transaction lifetime

P06

REPAIR importer isolation

P07

REPAIR statement ordering

P08

REPAIR isolation compatibility

P09

HOLD generation; REPAIR routing/provenance

P10

REPAIR partition plan; reject artifact

P11

ACCEPT only fresh generation after all gates

Repeatability and explicit ownership are the operational value of automating database acceptance checks: automation should make evidence reproducible, not turn a single success flag into an unjustified release decision.

The PostgreSQL contract supplies snapshot synchronization; the application must establish which generation was intended, whether each worker imported it, whether every assigned row was emitted exactly once, and whether the evidence bundle is complete. Only the conjunction earns ACCEPT.

Develop these skills with Refonte Learning’s Database Administrator Essentials

Refonte Learning’s Database Administrator Essentials program is a relevant foundation for engineers who want more structured work in database architecture, advanced SQL, query optimization, indexing, backup/recovery, performance, security, migration, integration, monitoring, and cloud database administration. The program page describes a three-month commitment of 12–14 hours per week, recommends basic programming knowledge, separately lists working toward a bachelor’s or higher degree as an admission prerequisite, and names AWS RDS, Azure SQL, and Google Cloud Spanner in its cloud path. It also describes mentoring, a potential internship, and Training and Internship Certificates on successful completion.

PostgreSQL exported-snapshot qualification, this particular coordinator, and the exact PostgreSQL 18.7/CPython 3.13.3 exercise have not been confirmed as curriculum items. The practical next step is therefore to use the program for the published SQL and database-operations foundations while treating this specialized shared-snapshot protocol as a separate lab that still requires its own documented acceptance evidence.