Postgres 25P02: put recovery at the right boundary
An illustrative import accepts a required record and attempts an optional annotation. Decide whether annotation failure invalidates the import before choosing a savepoint.
Quick answer
Postgres SQLSTATE `25P02` means an earlier statement left the transaction in a failed state. Find that original error before changing the query that reported it. Recover with a full rollback, or roll back to a savepoint established before the failure when the surrounding business operation is allowed to continue.
On this page
Postgres SQLSTATE 25P02 means an earlier statement left the transaction in a failed state. Find that original error before changing the query that reported it. Recover with a full rollback, or roll back to a savepoint established before the failure when the surrounding business operation is allowed to continue. [1][5]
Scenario: an import creates a required record, then stores an optional annotation. The annotation violates a uniqueness rule. Application code catches the error and continues to a final query, which reports “current transaction is aborted.” The final query is a witness to the failure, not necessarily its cause. Retrying that query alone cannot decide whether the required record should survive.
This article develops that decision using PostgreSQL transaction commands and a Psycopg example. The SQL case is deliberately small enough to inspect from another session. It is an illustrative import, not an account of a client incident. The reference behavior comes from PostgreSQL’s versioned documentation; driver transaction ownership must also be checked against the interface your application actually uses. [1][6]
What failed before 25P02?#
The useful error is usually earlier in the same transaction. Preserve its SQLSTATE, constraint name where available, operation identifier and transaction context. PostgreSQL recommends checking error codes instead of matching localized message strings. In this case, a duplicate annotation is materially different from a lost connection, invalid SQL or an unexpected required-record failure. [5]
Build a short trace: transaction entered, required insert returned, annotation insert failed, exception caught, later query refused. Include connection or request correlation without recording sensitive parameter values. The trace should make it possible to identify the first failed database operation even if later errors are more numerous.
Do not “fix” the later query by moving it to another connection while leaving ownership unclear. That may make the query execute, but it does not resolve whether the original transaction should commit or roll back. The import needs a single decision about its required work before reporting success to a caller.
Psycopg can start a transaction on an ordinary database operation by default. A preliminary read can therefore establish an outer transaction before a helper opens its own transaction context. The helper may then own only a savepoint. Read the driver’s transaction management rules before assuming that leaving a context commits the entire operation. [6]
Separate failure diagnosis from recovery scope. Use the first error to diagnose the failure, then use the import’s business rule to decide what may remain. A savepoint is appropriate only after those questions agree that the earlier work is valid independently of the failed optional step. If the annotation is required for audit or downstream interpretation, calling it optional in code does not make partial success acceptable.
Reproduce the boundary with an optional annotation#
Use an isolated database or temporary tables to make the behavior visible. The setup below creates a required imported record and a globally unique annotation token. The duplicate token represents an expected optional conflict. The required record uses a different key so that the failure cannot be mistaken for an import identity collision.
-- Illustrative scratch-session setup.
CREATE TEMP TABLE imported_record (
record_id text PRIMARY KEY,
payload text NOT NULL
);
CREATE TEMP TABLE import_annotation (
token text PRIMARY KEY,
record_id text NOT NULL
);
INSERT INTO import_annotation VALUES ('note-used', 'earlier-record');
BEGIN;
INSERT INTO imported_record VALUES ('batch-a', 'accepted payload');
INSERT INTO import_annotation VALUES ('note-used', 'batch-a');
-- Expected: unique violation. The next query is not the cause.
SELECT record_id FROM imported_record;
-- Expected: failed-transaction error.
ROLLBACK;
SELECT record_id FROM imported_record;
-- Expected: no imported row from this transaction.The expected results are part of the experiment, not a substitute for executing it in your own driver. A full rollback discards the required insert as well as the failed annotation attempt. That is correct if the operation is atomic as a whole. Do not treat the absence of an imported row as data loss caused by the rollback; it is the agreed failure outcome. [1]
Now write the intended alternative in plain language: “An import may succeed without an annotation when the annotation token already exists. Other database errors fail the import.” This rule is narrower than “ignore annotation errors.” It identifies the error the application may absorb and leaves unexpected failures visible.
That distinction also changes the response contract. A caller should receive an accepted import with an explicit annotation outcome, rather than a generic success flag that implies every requested side effect happened. The record identifier, optional-step result and failure reason can then be inspected together. Avoid claiming an annotation was saved merely because the required insert committed.
When is a savepoint the correct recovery scope?#
A savepoint is correct when established before the optional work and when rolling back that work leaves an acceptable operation. PostgreSQL cannot roll back to a savepoint that was never created, and savepoints must be established inside a transaction block. Creating one after the transaction has already failed cannot retroactively protect earlier work. [2][3]
BEGIN;
INSERT INTO imported_record VALUES ('batch-b', 'accepted payload');
SAVEPOINT optional_annotation;
INSERT INTO import_annotation VALUES ('note-used', 'batch-b');
-- Expected optional conflict; recovery belongs here.
ROLLBACK TO SAVEPOINT optional_annotation;
RELEASE SAVEPOINT optional_annotation;
SELECT record_id FROM imported_record WHERE record_id = 'batch-b';
COMMIT;
SELECT record_id FROM imported_record WHERE record_id = 'batch-b';
-- Expected: batch-b exists; the old annotation remains unchanged.Rolling back to the savepoint removes effects after the mark while retaining earlier work. Releasing it then removes the recovery mark; release is not a substitute for rollback in an aborted state. PostgreSQL explicitly rejects releasing a savepoint while the transaction is aborted. The ordering in the example is therefore part of the repair. [1][4]
Keep the savepoint around the smallest meaningful optional unit. If preparing the annotation changes other tables before its final insert fails, those changes belong inside the same optional scope. Otherwise a partial annotation can survive even though its main row was rejected. Review the actual helper’s queries, not only the statement that surfaced the error.
Avoid treating a savepoint as a local commit. Earlier work and successful optional work still depend on the outer transaction’s eventual outcome. An outer failure can roll them back later. Report durable success only at the layer that knows the business transaction completed, and keep that layer responsible for the final response. [1][4]
A savepoint gives the importer another recovery path to maintain. A savepoint adds another state transition and another outcome to test. For an all-or-nothing import, a full rollback is easier to explain. For a genuinely optional annotation, the extra boundary can preserve useful work without hiding the conflict. The choice follows the product contract rather than the convenience of an exception handler.
Where should application code catch the exception?#
Catch the expected exception outside the transaction context that must roll back. Psycopg transaction contexts commit or roll back when their scope exits; nested transaction contexts use savepoints. If the exception is swallowed inside the inner scope, the context cannot handle the original exception in the intended way. A reviewer should be able to see the transaction scope and its exception handler together. [6]
# Illustrative Psycopg 3 fragment; schema matches the SQL lab.
# The caller supplies DSN and a fresh operation identifier.
import psycopg
from psycopg.errors import UniqueViolation
def import_record(dsn, record_id, payload, annotation_token):
annotation_saved = True
with psycopg.connect(dsn, autocommit=True) as conn:
with conn.transaction():
conn.execute(
"INSERT INTO imported_record VALUES (%s, %s)",
(record_id, payload),
)
try:
with conn.transaction():
conn.execute(
"INSERT INTO import_annotation VALUES (%s, %s)",
(annotation_token, record_id),
)
except UniqueViolation as exc:
if exc.diag.constraint_name != "import_annotation_pkey":
raise
annotation_saved = False
# The business transaction has now left its owning context.
return {"record_id": record_id, "annotation_saved": annotation_saved}The temporary-table SQL lab and this connection-owning function are separate demonstrations. Temporary tables from another session are not available to the function’s new connection. To execute the function, create equivalent tables in a disposable schema accessible to that connection, then clean up that schema. This distinction matters when translating a readable SQL example into a driver test.
The function deliberately owns a fresh autocommit connection before starting an explicit transaction. It avoids an unnoticed earlier read creating an outer transaction. In an application that receives an existing connection, do not copy that ownership model silently. State whether the caller or helper owns commit, rollback and connection return. Psycopg documents how a context may manage only a savepoint when a transaction is already active. [6]
The constraint-name check is part of the illustrative contract. A different schema name or migration can change it, so keep it aligned with the deployed constraint. Catching every integrity error would also absorb unexpected required relationships or malformed data. Catching every exception would obscure network, programming and transaction failures that deserve a different response.
Do not return from inside a partially completed business scope merely because the required insert produced a row. If the outer transaction later fails, that row was never durable success. Place success reporting after the owner’s completion boundary and let unexpected exceptions escape to the layer that can mark the operation failed.
What proves the operation really committed?#
Verify persisted business state from outside the completed transaction, together with the optional-step outcome. A log saying “caught duplicate” does not establish that the required record survived. A connection that can execute another query is useful evidence of recovery, but it is a different assertion from successful commit.
| Case | Expected business outcome | Evidence to inspect |
|---|---|---|
| No conflict | Record and annotation accepted | Both rows visible after completion |
| Expected optional conflict | Record accepted, annotation skipped | Record visible; original token unchanged |
| Unexpected annotation error | Import fails | Required row absent after rollback |
| Required insert failure | Import fails | No optional operation reported as successful |
| Outer failure after optional work | Import fails | No new record or annotation survives |
Add a caller-owned transaction case if helpers accept existing connections. Begin work before calling the helper, then deliberately fail the outer operation. The expected result should show that the helper’s savepoint did not commit independently. That control is more useful than checking only the easy path through a fresh connection.
Define a separate outcome for uncertainty at the final acknowledgment boundary. If the connection disappears while the caller expects completion, do not infer the persisted state from the earlier optional-conflict handler. Use the import identifier to reconcile authoritative state before deciding whether a retry is safe. The small lab demonstrates database recovery scope; it does not implement a durable retry receipt.
Review the success response with the consuming team. In the optional-conflict case, “accepted with annotation skipped” should be a supported result, with the import identifier available for later inspection. If a downstream consumer requires the annotation to interpret the record, the example’s partial-success rule is wrong for that workflow. Move the annotation back into the required unit and fail the import together.
Keep tests for these business outcomes beside transaction tests. The database can correctly preserve the required row while the application still sends a misleading response. Conversely, a correct response shape cannot compensate for a helper that leaves its caller’s transaction unresolved. Verify both the persisted row and the externally reported outcome before closing the incident.
For pooled applications, include the next borrower in the verification plan. The borrower should receive the documented clean transaction state, and a failed operation should have a trace identifying its original error. Pool reset behavior is library-specific; confirm it instead of assuming a generic rollback rule proves every integration is correct.
Read idle transaction diagnosis when connections remain open after errors, and deadlock recovery when the original error requires retrying a larger unit. The failed-transaction message alone does not choose either remedy.
Frequently asked questions#
- Should I retry the statement reporting 25P02?
- First identify the earlier failure and restore transaction control. The later statement is running in an already failed transaction. Retrying it without rollback does not repair that state or establish which part of the business operation should survive. [1][5]
- Can I create a savepoint after the error?
- Plan the savepoint before the operation that may fail. It marks a state to return to inside an existing transaction. A name that was never established is invalid, so a newly imagined recovery point cannot preserve earlier work retroactively. [2][3]
- Is RELEASE SAVEPOINT enough to recover?
- Release discards the savepoint while keeping accepted changes within the surrounding transaction. It cannot be used to recover an aborted transaction. Roll back to the existing savepoint first when that is the intended scope, then release it. [2][4]
- Does leaving a Psycopg transaction context always commit?
- A context entered while no transaction is active can own the transaction. If a transaction already exists, a nested context may manage a savepoint instead. Confirm connection state and ownership before interpreting context exit as completion of the whole business operation. [6]