SQLite trigger failure analysis comparing partial writes, transaction rollback, and savepoint recovery

A SQLite Trigger Rejected the Insert. Which Writes Survived?

Mon, Nov 30, 2026

A SQLite INSERT can raise an error and still leave database changes pending in the writer’s transaction. With an explicit trigger that first increments a counter and then calls RAISE(FAIL, 'REJECTED_BY_TRIGGER'), a BEFORE INSERT trigger can leave the counter increment behind even though the candidate row was never inserted. An AFTER INSERT trigger can leave both the source row and the counter change behind. SQLite documents that RAISE(FAIL) applies the FAIL conflict response; FAIL terminates the statement without backing out changes already made by that statement and does not end the transaction. ABORT, by contrast, backs out the current statement while preserving prior statements in the transaction, and ROLLBACK rolls back the transaction.

The operational problem is therefore not “did Python raise IntegrityError?” It is “which write set still exists, who owns the recovery boundary, and what evidence proves that state?” The controlled fixture below has three independent dimensions: earlier transaction work represented by marker A; candidate row (41,'candidate'); and counter row (1,n). One writer owns the explicit transaction. Short-lived read-only connections observe only resolved committed state.

Everything below is practitioner reasoning derived from the documented mechanisms, not a claim of personal incidents or laboratory observation. All case outcomes are EXPECTED / NOT EXECUTED until somebody runs the complete harness and retains its runtime, schema, exception, tuple, transaction-state, and observer evidence.

Execution status: EXPECTED / NOT EXECUTED. No laboratory run accompanied this article. The proposed reference build is CPython 3.12.16 with SQLite 3.54.1 linked to Python’s sqlite3 module; the published versions are verified, but that combination has not been built or tested here. Python 3.12.16 is an official release, and SQLite 3.54.1 is an official SQLite release dated 2026-10-16.

Define the state a rejected insert must leave behind

A backend cannot choose recovery correctly until it defines what “reject the insert” means at the application boundary. There are two legitimate contracts in this fixture.

The first contract is reject only the candidate. Earlier authorized work in the transaction must remain. If marker A was written before the candidate started, rejecting candidate 41 should preserve A while removing every effect attributable to the candidate statement. This contract needs a statement-sized or candidate-sized recovery boundary.

The second contract is abandon the entire owned unit. If candidate rejection invalidates the complete transaction, marker A must disappear too. That contract needs transaction rollback, not merely statement repair.

Those contracts are different because the fixture contains three tables:

CREATE TABLE outer_work(token TEXT PRIMARY KEY);
CREATE TABLE requests(id INTEGER PRIMARY KEY, payload TEXT NOT NULL);
CREATE TABLE counters(id INTEGER PRIMARY KEY, value INTEGER NOT NULL);

outer_work represents earlier transaction work. requests holds the candidate source row. counters exposes a trigger side effect separately from the source row. The separation is deliberate: an error can affect these dimensions differently.

The writer’s state is provisional until the transaction resolves. A fresh read-only observer is therefore part of the evidence model. While the writer owns an uncommitted transaction, a separate observer should still see the committed baseline; after an authorized commit or rollback, a reopened observer shows the resolved state. This article does not treat the writer’s pending view as a committed result.

That concern is distinct from Refonte Learning’s article on post-trigger stored-value validation, which examines a successful top-level write whose returned values can differ from final trigger-modified storage. Here the top-level INSERT is rejected and the question is which writes remain pending after that explicit rejection.

A useful recovery review therefore asks three separate questions: did earlier outer work survive, did the candidate row survive, and did the trigger’s preceding side effect survive? Only after answering all three should an owner decide whether to repair, roll back a candidate boundary, roll back the whole unit, or hold.

Separate error reporting from the three rollback scopes

RAISE() inside a SQLite trigger does two things relevant here: it terminates the current query and selects a specified conflict-processing action when the action is ROLLBACK, ABORT, or FAIL. SQLite documents this explicitly in CREATE TRIGGER.

The rollback scopes are not interchangeable:

Explicit trigger action

Expected scope in this fixture

Transaction afterward

RAISE(FAIL, ...)

Stop the statement but preserve changes already made by that statement

Active

RAISE(ABORT, ...)

Back out changes made by the current statement; preserve earlier statements

Active

RAISE(ROLLBACK, ...)

Roll back the enclosing transaction

Inactive

SQLite’s ON CONFLICT documentation states that FAIL does not back out prior changes of the failed statement and does not end the transaction; ABORT backs out changes from the current statement while preserving earlier statements in the transaction; and ROLLBACK rolls back the current transaction. Here those algorithms are selected explicitly through trigger RAISE(), as documented by the trigger reference.

The exception is therefore evidence that the request failed, but it is not sufficient evidence of rollback scope. A Python IntegrityError cannot tell an operator whether the counter remains at 1, the candidate row remains present, or the outer marker survived. Those are state questions.

This is also different from SQLite conflict handling that hides invalid rows. IGNORE can suppress an applicable constraint error and silently skip work; this fixture deliberately raises an explicit trigger error. The operational trap here is almost the inverse: an error is visible, yet some writes can still survive.

The discussion is intentionally confined to explicit RAISE(FAIL), RAISE(ABORT), and RAISE(ROLLBACK) in the measured trigger. It does not claim that every SQLite error family, CHECK failure, foreign-key failure, I/O failure, or interruption follows the same state transitions.

Pin the runtime, trigger, and transaction owner

A rollback-scope experiment is meaningful only if the transaction owner and runtime are explicit.

Each case uses a fresh file in a temporary directory, one writer connection, no connection pool, no attached databases, no external side effects, and short-lived read-only observer connections. The Python connection is opened with autocommit=True, then transaction control is expressed only as SQL: BEGIN, COMMIT, ROLLBACK, SAVEPOINT, ROLLBACK TO, and RELEASE.

Python 3.12 documents that the autocommit parameter was added in Python 3.12. When it is True, SQLite’s own autocommit mode is used and Python Connection.commit() and Connection.rollback() have no effect. Connection.in_transaction exposes the low-level transaction state.

That is why this fixture does not mix SQL transaction commands with method calls.

Before measurement, it executes and verifies:

PRAGMA journal_mode=DELETE;

SQLite documents that journal mode OFF disables normal rollback capabilities and makes ROLLBACK behavior undefined; this experiment therefore rejects a fixture whose reported mode is not delete.

Every observer opens the same database through a mode=ro URI, fetches its complete state, and closes before the writer is resolved. There is no executescript(), connection context manager, ORM session, or Python rollback method in the measured path.

The neighboring Refonte analysis of Python executescript and pending commits addresses a driver/script boundary that could change transaction ownership before later SQL executes. This fixture excludes that mechanism so the measured rollback scope comes from explicit SQLite commands and the trigger-selected action.

Record the actual interpreter, engine, and installed trigger

The proposed reference identity is CPython 3.12.16 plus SQLite 3.54.1. Python.org verifies the 3.12.16 release, while SQLite’s 3.54.1 release page identifies that engine release and its source ID. Neither page proves that a particular Python binary links that SQLite library.

A real run must therefore capture, not assume:

platform.python_version()
sqlite3.sqlite_version
SELECT sqlite_source_id()
PRAGMA journal_mode
SELECT sql FROM sqlite_schema
WHERE type='trigger' AND name='reject_candidate'

sqlite3.sqlite_version identifies the runtime SQLite library reported through Python; sqlite_source_id() gives a more specific SQLite source identifier. SQLite’s published 3.54.1 source ID corresponds to that release, but the harness records whatever it actually receives.

The trigger SQL is evidence too. A result from AFTER FAIL is not transferable to an unrecorded BEFORE ABORT trigger. Exactly one measured trigger is installed per case, and its timing and action are part of the record.

Build a single-row fixture with independent expectations

The baseline schema is fixed:

CREATE TABLE outer_work(token TEXT PRIMARY KEY);
CREATE TABLE requests(id INTEGER PRIMARY KEY, payload TEXT NOT NULL);
CREATE TABLE counters(id INTEGER PRIMARY KEY, value INTEGER NOT NULL);
INSERT INTO counters(id, value) VALUES(1, 0);

Before each case’s first measured candidate attempt, the writer executes:

BEGIN;
INSERT INTO outer_work(token) VALUES('A');

INSERT INTO requests(id, payload)
VALUES(?, ?);

The parameters are always:

(41, "candidate")

T09 is the only repeated-attempt control. Its second candidate attempt occurs in the same still-active transaction. It does not execute another BEGIN and does not insert marker A again.

The failure-producing trigger template is:

CREATE TRIGGER reject_candidate
TIMING INSERT ON requests
BEGIN
  UPDATE counters
     SET value = value + 1
   WHERE id = 1;

  SELECT RAISE(ACTION, 'REJECTED_BY_TRIGGER');
END;

TIMING is controlled as either BEFORE or AFTER; ACTION is controlled as FAIL, ABORT, or ROLLBACK. These fragments are authored fixture constants, not user input.

SQLite defines BEFORE and AFTER as positioning trigger actions relative to the source-row operation. It also cautions about certain source-row mutations in BEFORE triggers and notes that a BEFORE INSERT trigger has an undefined NEW.rowid if it was not explicitly set to an integer. This fixture avoids those hazards: it modifies a separate counter table and supplies explicit integer ID 41.

The literal message is intentional. SQLite has allowed expression-valued RAISE messages since 3.47.0, but this fixture does not depend on that newer syntax and makes no novelty claim.

Author the three-table oracle before reading the database

Expectations must not be inferred from the database under test. The oracle is authored beforehand as exact sorted tuples:

B   = ([], [], [(1, 0)])

A0  = ([('A',)], [], [(1, 0)])

A1  = ([('A',)], [], [(1, 1)])

AR1 = ([('A',)], [(41, 'candidate')], [(1, 1)])

A2  = ([('A',)], [], [(1, 2)])

The tuple order is:

(outer_work rows, requests rows, counters rows)

Before every case’s first measured attempt, the writer must equal A0, Connection.in_transaction must be true, and a fresh read-only observer must equal B.

Before T09’s second attempt, the writer must equal A1, the transaction must remain active, and the observer must still equal B.

Aliases are only labels for these literals. The harness never asks the tested database to generate its own expected state.

That independence matters operationally. If an unexpected run produced a counter of 7, code that simply stored “whatever the database returned” as its expected value would transform a discrepancy into a false pass. The oracle must be able to contradict the implementation.

Establish the successful trigger control

T01 proves the fixture can perform the ordinary row insert, execute an AFTER INSERT counter update, distinguish writer-visible state from observer-visible committed state, and resolve through explicit SQL.

Its trigger is:

CREATE TRIGGER reject_candidate
AFTER INSERT ON requests
BEGIN
  UPDATE counters
     SET value = value + 1
   WHERE id = 1;
END;

There is no RAISE.

The EXPECTED / NOT EXECUTED sequence is:

writer before candidate: A0, transaction active
candidate succeeds
writer after candidate:  AR1, transaction active
fresh observer:           B
SQL COMMIT
reopened state:           AR1
writer transaction flag:  false

The observer remaining at B before resolution is what keeps “pending survivor” separate from “committed result.” T01 does not establish power-loss durability; it only establishes ordinary SQL resolution and subsequent readback within the stated fixture.

The complete standard-library harness is below. It intentionally has one entry point, closes cursors/connections explicitly, records evidence before cleanup, and asserts every expected tuple, transaction flag, exception field, recovery checkpoint, observer view, and case ID.

#!/usr/bin/env python3
import json
import platform
import sqlite3
import tempfile
from pathlib import Path

B = ([], [], [(1, 0)])
A0 = ([("A",)], [], [(1, 0)])
A1 = ([("A",)], [], [(1, 1)])
AR1 = ([("A",)], [(41, "candidate")], [(1, 1)])
A2 = ([("A",)], [], [(1, 2)])

EXPECTED_IDS = {
    "T01", "T02", "T03", "T04", "T05",
    "T06", "T07", "T08", "T09", "T10",
}

EXPECTED_FINAL = {
    "T01": AR1,
    "T02": A1,
    "T03": A0,
    "T04": AR1,
    "T05": A0,
    "T06": B,
    "T07": A0,
    "T08": B,
    "T09": A2,
    "T10": B,
}

SCHEMA = """
CREATE TABLE outer_work(token TEXT PRIMARY KEY);
CREATE TABLE requests(id INTEGER PRIMARY KEY, payload TEXT NOT NULL);
CREATE TABLE counters(id INTEGER PRIMARY KEY, value INTEGER NOT NULL);
INSERT INTO counters(id, value) VALUES(1, 0);
"""

CANDIDATE_SQL = """
INSERT INTO requests(id, payload) VALUES(?, ?)
"""

def fetch_state(conn):
    cur = conn.cursor()
    try:
        outer_rows = cur.execute(
            "SELECT token FROM outer_work ORDER BY token"
        ).fetchall()
        request_rows = cur.execute(
            "SELECT id, payload FROM requests ORDER BY id"
        ).fetchall()
        counter_rows = cur.execute(
            "SELECT id, value FROM counters ORDER BY id"
        ).fetchall()
        return (outer_rows, request_rows, counter_rows)
    finally:
        cur.close()

def assert_equal(actual, expected, label):
    if actual != expected:
        raise AssertionError(
            f"{label}: expected {expected!r}, got {actual!r}"
        )

def assert_tx(conn, expected, label):
    assert_equal(conn.in_transaction, expected, label)

def readonly_state(path):
    uri = path.resolve().as_uri() + "?mode=ro"
    conn = sqlite3.connect(uri, uri=True, autocommit=True)
    try:
        return fetch_state(conn)
    finally:
        conn.close()

def serialize_error(exc):
    return {
        "type": type(exc).__name__,
        "message": str(exc),
        "sqlite_errorcode": getattr(exc, "sqlite_errorcode", None),
        "sqlite_errorname": getattr(exc, "sqlite_errorname", None),
    }

def assert_trigger_error(exc):
    if not isinstance(exc, sqlite3.IntegrityError):
        raise AssertionError(
            f"expected sqlite3.IntegrityError, got {type(exc)!r}"
        )
    record = serialize_error(exc)
    assert_equal(
        record["message"],
        "REJECTED_BY_TRIGGER",
        "trigger error message",
    )
    assert_equal(
        record["sqlite_errorcode"],
        1811,
        "trigger extended error code",
    )
    assert_equal(
        record["sqlite_errorname"],
        "SQLITE_CONSTRAINT_TRIGGER",
        "trigger extended error name",
    )
    return record

def create_trigger(conn, timing, action=None):
    if timing not in {"BEFORE", "AFTER"}:
        raise ValueError(timing)

    if action is None:
        sql = f"""
        CREATE TRIGGER reject_candidate
        {timing} INSERT ON requests
        BEGIN
          UPDATE counters
             SET value = value + 1
           WHERE id = 1;
        END
        """
    else:
        if action not in {"FAIL", "ABORT", "ROLLBACK"}:
            raise ValueError(action)
        sql = f"""
        CREATE TRIGGER reject_candidate
        {timing} INSERT ON requests
        BEGIN
          UPDATE counters
             SET value = value + 1
           WHERE id = 1;
          SELECT RAISE({action}, 'REJECTED_BY_TRIGGER');
        END
        """

    conn.execute(sql)

def setup(path, timing, action=None):
    conn = sqlite3.connect(path, autocommit=True)

    mode = conn.execute(
        "PRAGMA journal_mode=DELETE"
    ).fetchone()[0].lower()
    assert_equal(mode, "delete", "journal mode")

    conn.execute(
        "CREATE TABLE outer_work(token TEXT PRIMARY KEY)"
    )
    conn.execute(
        "CREATE TABLE requests("
        "id INTEGER PRIMARY KEY, "
        "payload TEXT NOT NULL)"
    )
    conn.execute(
        "CREATE TABLE counters("
        "id INTEGER PRIMARY KEY, "
        "value INTEGER NOT NULL)"
    )
    conn.execute(
        "INSERT INTO counters(id, value) VALUES(1, 0)"
    )

    create_trigger(conn, timing, action)

    trigger_sql = conn.execute(
        """
        SELECT sql
          FROM sqlite_schema
         WHERE type='trigger'
           AND name='reject_candidate'
        """
    ).fetchone()[0]

    source_id = conn.execute(
        "SELECT sqlite_source_id()"
    ).fetchone()[0]

    assert_equal(fetch_state(conn), B, "committed baseline")
    assert_tx(conn, False, "baseline transaction state")

    runtime = {
        "python_version": platform.python_version(),
        "sqlite_version": sqlite3.sqlite_version,
        "sqlite_source_id": source_id,
        "journal_mode": mode,
        "trigger_sql": trigger_sql,
        "timing": timing,
        "action": action,
    }
    return conn, runtime

def prepare_outer(conn, path, evidence):
    conn.execute("BEGIN")
    conn.execute(
        "INSERT INTO outer_work(token) VALUES('A')"
    )

    writer = fetch_state(conn)
    observer = readonly_state(path)

    assert_equal(writer, A0, "pre-attempt writer state")
    assert_tx(conn, True, "pre-attempt transaction")
    assert_equal(observer, B, "pre-attempt observer state")

    evidence["checkpoints"].append({
        "name": "before_first_attempt",
        "writer": writer,
        "in_transaction": conn.in_transaction,
        "observer": observer,
    })

def attempt_rejected_insert(conn, evidence, name):
    try:
        conn.execute(CANDIDATE_SQL, (41, "candidate"))
    except Exception as exc:
        record = assert_trigger_error(exc)
        evidence["exceptions"].append({
            "attempt": name,
            **record,
        })
        return
    raise AssertionError("expected trigger rejection, got success")

def observe_checkpoint(conn, path, evidence, name, expected):
    writer = fetch_state(conn)
    observer = readonly_state(path)

    assert_equal(writer, expected, f"{name} writer")
    assert_equal(observer, B, f"{name} observer")

    evidence["checkpoints"].append({
        "name": name,
        "writer": writer,
        "in_transaction": conn.in_transaction,
        "observer": observer,
    })

def reopen_state(path):
    conn = sqlite3.connect(path, autocommit=True)
    try:
        state = fetch_state(conn)
        tx = conn.in_transaction
        return state, tx
    finally:
        conn.close()

def finalize_evidence(path, evidence, expected_final):
    state, tx = reopen_state(path)
    assert_equal(state, expected_final, "final reopened state")
    assert_equal(tx, False, "final reopened transaction state")
    evidence["reopened_state"] = state
    evidence["reopened_in_transaction"] = tx

def new_evidence(case_id, runtime):
    return {
        "case_id": case_id,
        "execution_label": "ACTUAL_IF_THIS_HARNESS_IS_RUN",
        "runtime": runtime,
        "exceptions": [],
        "checkpoints": [],
        "recovery_sequence": [],
        "reopened_state": None,
        "reopened_in_transaction": None,
    }

def run_case(root, case_id):
    specs = {
        "T01": ("AFTER", None),
        "T02": ("BEFORE", "FAIL"),
        "T03": ("BEFORE", "ABORT"),
        "T04": ("AFTER", "FAIL"),
        "T05": ("AFTER", "ABORT"),
        "T06": ("AFTER", "ROLLBACK"),
        "T07": ("AFTER", "FAIL"),
        "T08": ("AFTER", "FAIL"),
        "T09": ("BEFORE", "FAIL"),
        "T10": ("AFTER", "FAIL"),
    }
    timing, action = specs[case_id]
    path = root / f"{case_id}.sqlite"

    conn, runtime = setup(path, timing, action)
    evidence = new_evidence(case_id, runtime)

    try:
        prepare_outer(conn, path, evidence)

        if case_id == "T01":
            conn.execute(CANDIDATE_SQL, (41, "candidate"))
            observe_checkpoint(
                conn, path, evidence,
                "after_success", AR1
            )
            assert_tx(conn, True, "T01 before commit")
            conn.execute("COMMIT")
            evidence["recovery_sequence"].append("COMMIT")
            assert_tx(conn, False, "T01 after commit")
            finalize_evidence(path, evidence, AR1)

        elif case_id == "T02":
            attempt_rejected_insert(conn, evidence, "attempt_1")
            observe_checkpoint(
                conn, path, evidence,
                "after_error", A1
            )
            assert_tx(conn, True, "T02 after error")
            conn.execute("COMMIT")
            evidence["recovery_sequence"].append(
                "DIAGNOSTIC COMMIT"
            )
            assert_tx(conn, False, "T02 after commit")
            finalize_evidence(path, evidence, A1)

        elif case_id == "T03":
            attempt_rejected_insert(conn, evidence, "attempt_1")
            observe_checkpoint(
                conn, path, evidence,
                "after_error", A0
            )
            assert_tx(conn, True, "T03 after error")
            conn.execute("COMMIT")
            evidence["recovery_sequence"].append(
                "DIAGNOSTIC COMMIT"
            )
            assert_tx(conn, False, "T03 after commit")
            finalize_evidence(path, evidence, A0)

        elif case_id == "T04":
            attempt_rejected_insert(conn, evidence, "attempt_1")
            observe_checkpoint(
                conn, path, evidence,
                "after_error", AR1
            )
            assert_tx(conn, True, "T04 after error")
            conn.execute("COMMIT")
            evidence["recovery_sequence"].append(
                "DIAGNOSTIC COMMIT"
            )
            assert_tx(conn, False, "T04 after commit")
            finalize_evidence(path, evidence, AR1)

        elif case_id == "T05":
            attempt_rejected_insert(conn, evidence, "attempt_1")
            observe_checkpoint(
                conn, path, evidence,
                "after_error", A0
            )
            assert_tx(conn, True, "T05 after error")
            conn.execute("COMMIT")
            evidence["recovery_sequence"].append("COMMIT")
            assert_tx(conn, False, "T05 after commit")
            finalize_evidence(path, evidence, A0)

        elif case_id == "T06":
            attempt_rejected_insert(conn, evidence, "attempt_1")
            assert_equal(
                fetch_state(conn), B,
                "T06 state after engine rollback"
            )
            assert_tx(
                conn, False,
                "T06 transaction after engine rollback"
            )
            observer = readonly_state(path)
            assert_equal(observer, B, "T06 observer")
            evidence["checkpoints"].append({
                "name": "after_engine_rollback",
                "writer": fetch_state(conn),
                "in_transaction": conn.in_transaction,
                "observer": observer,
            })
            evidence["recovery_sequence"].append(
                "NO EXTRA RESOLUTION"
            )
            finalize_evidence(path, evidence, B)

        elif case_id == "T07":
            conn.execute("SAVEPOINT candidate")
            evidence["recovery_sequence"].append(
                "SAVEPOINT candidate"
            )
            attempt_rejected_insert(conn, evidence, "attempt_1")
            observe_checkpoint(
                conn, path, evidence,
                "after_error", AR1
            )
            assert_tx(conn, True, "T07 after error")

            conn.execute("ROLLBACK TO candidate")
            evidence["recovery_sequence"].append(
                "ROLLBACK TO candidate"
            )
            observe_checkpoint(
                conn, path, evidence,
                "after_rollback_to", A0
            )
            assert_tx(conn, True, "T07 after rollback to")

            conn.execute("RELEASE candidate")
            evidence["recovery_sequence"].append(
                "RELEASE candidate"
            )
            observe_checkpoint(
                conn, path, evidence,
                "after_release", A0
            )
            assert_tx(conn, True, "T07 after release")

            conn.execute("COMMIT")
            evidence["recovery_sequence"].append("COMMIT")
            assert_tx(conn, False, "T07 after commit")
            finalize_evidence(path, evidence, A0)

        elif case_id == "T08":
            attempt_rejected_insert(conn, evidence, "attempt_1")
            observe_checkpoint(
                conn, path, evidence,
                "after_error", AR1
            )
            assert_tx(conn, True, "T08 after error")

            conn.execute("ROLLBACK")
            evidence["recovery_sequence"].append("ROLLBACK")
            assert_tx(conn, False, "T08 after rollback")
            finalize_evidence(path, evidence, B)

        elif case_id == "T09":
            attempt_rejected_insert(conn, evidence, "attempt_1")
            observe_checkpoint(
                conn, path, evidence,
                "after_first_error", A1
            )
            assert_tx(conn, True, "T09 after first error")

            attempt_rejected_insert(conn, evidence, "attempt_2")
            observe_checkpoint(
                conn, path, evidence,
                "after_second_error", A2
            )
            assert_tx(conn, True, "T09 after second error")

            assert_equal(
                len(evidence["exceptions"]), 2,
                "T09 exception count"
            )
            conn.execute("COMMIT")
            evidence["recovery_sequence"].append(
                "DIAGNOSTIC COMMIT"
            )
            assert_tx(conn, False, "T09 after commit")
            finalize_evidence(path, evidence, A2)

        elif case_id == "T10":
            conn.execute("SAVEPOINT candidate")
            evidence["recovery_sequence"].append(
                "SAVEPOINT candidate"
            )
            attempt_rejected_insert(conn, evidence, "attempt_1")
            observe_checkpoint(
                conn, path, evidence,
                "after_error", AR1
            )
            assert_tx(conn, True, "T10 after error")

            conn.execute("RELEASE candidate")
            evidence["recovery_sequence"].append(
                "RELEASE candidate"
            )
            observe_checkpoint(
                conn, path, evidence,
                "after_release_without_rollback_to", AR1
            )
            assert_tx(conn, True, "T10 after release")

            conn.execute("ROLLBACK")
            evidence["recovery_sequence"].append("ROLLBACK")
            assert_tx(conn, False, "T10 after rollback")
            finalize_evidence(path, evidence, B)

        else:
            raise AssertionError(f"unhandled case {case_id}")

        if action is not None and case_id != "T09":
            assert_equal(
                len(evidence["exceptions"]), 1,
                f"{case_id} exception count"
            )

        return evidence

    finally:
        # Cleanup is deliberately after measured checkpoints.
        # It never rewrites recorded evidence.
        if conn.in_transaction:
            conn.execute("ROLLBACK")
        conn.close()

def main():
    results = []

    with tempfile.TemporaryDirectory(
        prefix="sqlite-trigger-fail-"
    ) as temp_dir:
        root = Path(temp_dir)

        for case_id in sorted(EXPECTED_IDS):
            results.append(run_case(root, case_id))

    actual_ids = {record["case_id"] for record in results}
    assert_equal(actual_ids, EXPECTED_IDS, "case coverage")

    for record in results:
        case_id = record["case_id"]
        assert_equal(
            record["reopened_state"],
            EXPECTED_FINAL[case_id],
            f"{case_id} expected final state"
        )
        assert_equal(
            record["reopened_in_transaction"],
            False,
            f"{case_id} final transaction flag"
        )

    print(json.dumps(results, indent=2))

if name == "__main__":
    main()

A reproducible invocation is simply:

python3 sqlite_trigger_failure_scope.py > evidence.json

Running it would convert the case records from expected outcomes into actual fixture evidence only for the runtime and trigger DDL recorded in that output.

Inspect the counter left by a BEFORE failure

T02 uses BEFORE INSERT plus RAISE(FAIL, 'REJECTED_BY_TRIGGER').

The trigger runs before the source-row insertion. Its first step increments counters; the second invokes FAIL. SQLite documents both the timing relationship and the fact that FAIL does not back out prior changes made by the failed statement.

The EXPECTED / NOT EXECUTED result is therefore:

before candidate: A0
error: IntegrityError / trigger constraint
writer: A1
transaction: active
observer: B

The source row is absent because the BEFORE trigger rejects the statement before the insertion reaches the after-source-row point represented in this fixture. The counter increment, however, preceded the RAISE(FAIL) within the same statement and is expected to survive in the active transaction.

T02 then deliberately issues SQL COMMIT. That is a diagnostic control, not recommended request handling. The expected reopened state is A1: marker A plus counter 1, with no request row.

T03 changes only the action from FAIL to ABORT:

SELECT RAISE(ABORT, 'REJECTED_BY_TRIGGER');

SQLite documents ABORT as backing out changes made by the current SQL statement while preserving changes from prior statements in the transaction. Because the counter update is part of the candidate statement, it is expected to be undone; marker A, written by the preceding statement, remains. The transaction stays active.

Expected T03:

error: IntegrityError / trigger constraint
writer: A0
transaction: active
observer: B
diagnostic COMMIT
reopened: A0

The critical comparison is not “both raised.” It is A1 versus A0.

Repeat the rejected attempt without assuming it was harmless

T09 is deliberately narrow. It repeats the identical T02 candidate once in the same transaction:

BEGIN
INSERT marker A
attempt candidate 41 -> BEFORE FAIL -> error
attempt candidate 41 -> BEFORE FAIL -> error
diagnostic COMMIT

No second BEGIN occurs. Marker A is not inserted again.

After the first rejection, expected state is A1. The candidate row does not exist, so the same candidate statement can reach the same trigger again. Its trigger increments the counter from 1 to 2, then rejects again.

Expected state after the second exception is:

A2 = ([('A',)], [], [(1,2)])

Both exceptions must be retained separately in the evidence record. The observer remains B before resolution. Diagnostic COMMIT then makes A2 visible on reopen.

This control demonstrates one operational point only: a rejected RAISE(FAIL) statement is not automatically harmless to repeat. It does not define a retry algorithm, backoff policy, idempotency framework, or production replay strategy.

Check the source row after an AFTER failure

T04 holds the input, transaction, counter update, error message, and action constant while changing trigger timing to AFTER.

The trigger becomes:

CREATE TRIGGER reject_candidate
AFTER INSERT ON requests
BEGIN
  UPDATE counters
     SET value = value + 1
   WHERE id = 1;
  SELECT RAISE(FAIL, 'REJECTED_BY_TRIGGER');
END;

SQLite states that AFTER positions trigger actions after the associated row operation. FAIL then terminates the query without backing out earlier changes of that failed statement.

The expected causal sequence is therefore:

sqlite-trigger-img-first

The EXPECTED / NOT EXECUTED writer state is AR1:

outer_work: [('A',)]
requests:   [(41,'candidate')]
counters:   [(1,1)]

The fresh observer still reads B because the writer has not resolved the transaction. The word “survived” here means “remains in the writer’s pending transaction after statement rejection,” not “was automatically committed.”

A deliberate diagnostic COMMIT is expected to make AR1 visible to a reopened connection.

The BEFORE/AFTER comparison is the heart of the experiment:

Case

Timing/action

Error

Pending source row

Pending counter

T02

BEFORE FAIL

Yes

No

1

T04

AFTER FAIL

Yes

Yes

1

Nothing in that comparison relies on multirow visitation or ordering among multiple triggers; the fixture installs exactly one trigger and attempts one explicit integer row.

Compare statement rollback with whole-transaction rollback

T05 uses AFTER INSERT with RAISE(ABORT, ...). The source row is inserted and the trigger counter update executes before the failure, but ABORT is documented to back out changes made by the current statement. Earlier statements in the transaction remain, and the transaction stays active.

So T05 is expected to produce:

immediate writer: A0
transaction: active
observer: B
authorized COMMIT
reopened: A0

This is statement rollback: both candidate-row and trigger-counter effects disappear, but earlier marker A remains.

T06 changes only the action to ROLLBACK:

SELECT RAISE(ROLLBACK, 'REJECTED_BY_TRIGGER');

SQLite documents the ROLLBACK conflict response as aborting the statement and rolling back the current transaction when one is active. Since this fixture explicitly opened BEGIN, the expected result is immediate B and Connection.in_transaction == False.

The writer no longer owns a live transaction containing A; the fresh reader also sees B. The harness therefore performs no extra resolution command for T06. Blindly issuing another COMMIT or treating the transaction as still open would confuse the engine-selected rollback with an application-owned pending boundary.

SQLite separately warns that some other classes of errors, including certain I/O, full-disk, interrupt, or memory conditions, may affect transaction state differently depending on circumstances. Those are outside this qualification.

Interpret the error code without inferring the write set

For every RAISE case, the expected Python metadata is:

exception class:      sqlite3.IntegrityError
sqlite_errorcode:     1811
sqlite_errorname:     SQLITE_CONSTRAINT_TRIGGER
message:              REJECTED_BY_TRIGGER

SQLite defines extended result code 1811, SQLITE_CONSTRAINT_TRIGGER, as indicating that a RAISE function in a trigger fired and caused the SQL statement to abort.

That code identifies the trigger-origin rejection. It does not encode whether the selected action was FAIL, ABORT, or ROLLBACK, and therefore does not identify the surviving write set.

T02 can report 1811 while the writer is A1. T04 can report the same code while the writer is AR1. T05 can report it while the writer is A0. T06 can report it after the entire transaction has become B.

The exception record must therefore be paired with exact tuple state and transaction state. If an actual run produces different metadata (different exception class, code, name, or message), the correct classification is not “close enough.” It is failed qualification and therefore HOLD until the discrepancy is understood.

Restore only the candidate with an owned savepoint

T07 demonstrates an application-owned boundary that is narrower than the outer transaction.

The ordering is exact:

BEGIN;
INSERT INTO outer_work(token) VALUES('A');

SAVEPOINT candidate;

INSERT INTO requests(id, payload)
VALUES(41, 'candidate');
-- AFTER trigger increments counter, then RAISE(FAIL)

ROLLBACK TO candidate;
RELEASE candidate;

COMMIT;

Immediately after the AFTER FAIL error, T07 is expected to equal AR1 and remain in an active transaction, exactly like T04.

SQLite documents ROLLBACK TO as restoring database state to just after the named savepoint while leaving the outer transaction active. RELEASE removes the named savepoint; for an inner savepoint it does not independently write changes to the database file or commit the enclosing transaction.

Therefore:

after error:                 AR1, active
ROLLBACK TO candidate:       A0, active
RELEASE candidate:           A0, active
observer before outer commit B
outer COMMIT
reopened:                    A0, inactive

This is the candidate-only recovery contract. Marker A was created before the savepoint, so it remains. Candidate row and trigger counter increment happened after the savepoint, so both are rewound.

The neighboring article on SQLAlchemy savepoint scope and pending flush addresses a different ownership risk: ORM work can occur before an intended nested boundary. This fixture contains no ORM and no flush. Its savepoint is explicit SQL and is established before the candidate statement.

Placement remains critical. A savepoint created after the candidate cannot retroactively protect it.

Likewise, a trigger-selected RAISE(ROLLBACK) cannot be treated as though the named savepoint necessarily remains available. In this fixture, RAISE(ROLLBACK) ends the enclosing transaction; recovery code must inspect transaction state instead of blindly assuming its savepoint survived. SQLite’s transaction and savepoint documentation define those scopes separately.

Test RELEASE-only handling and complete rollback

T10 tests a common savepoint misconception: that RELEASE candidate somehow undoes failed candidate work.

The setup matches T07 through the error:

BEGIN
insert A
SAVEPOINT candidate
AFTER FAIL candidate
writer = AR1
transaction active

Then T10 executes only:

RELEASE candidate;

SQLite describes RELEASE as removing savepoints from the transaction stack; for an inner savepoint it does not itself undo the changes made since that savepoint.

The expected result immediately after RELEASE is therefore still:

AR1, transaction active
observer B

T10 then executes outer SQL ROLLBACK, producing reopened B. The important evidence is the intermediate AR1 checkpoint: reaching baseline eventually does not make RELEASE a candidate rollback operation.

T08 provides the whole-unit control without a savepoint. After AFTER FAIL, it captures expected AR1 with an active transaction, then the transaction owner executes:

ROLLBACK;

A reopened observer must then see B, including removal of marker A.

T07 and T08 therefore establish different scopes even though both can remove the rejected candidate:

T07 ROLLBACK TO candidate -> preserves A
T08 ROLLBACK              -> removes A

T10 establishes something else again:

RELEASE candidate         -> removes the boundary, not the writes
outer ROLLBACK            -> later removes the entire unit

Recovery review should compare the intermediate checkpoints, not merely the final database.

Reconcile all ten cases before interpreting the result

The table below is the complete EXPECTED / NOT EXECUTED matrix. All pre-resolution read-only observers are expected to see B. Every reopened final transaction flag is expected to be false.

ID

Trigger

Attempts

Immediate writer state

Tx active immediately?

Recovery checkpoint(s)

Final action

Reopened state

T01

AFTER, no RAISE

1

AR1

Yes

Observer B

COMMIT

AR1

T02

BEFORE FAIL

1

A1

Yes

Observer B

Diagnostic COMMIT

A1

T03

BEFORE ABORT

1

A0

Yes

Observer B

Diagnostic COMMIT

A0

T04

AFTER FAIL

1

AR1

Yes

Observer B

Diagnostic COMMIT

AR1

T05

AFTER ABORT

1

A0

Yes

Observer B

COMMIT

A0

T06

AFTER ROLLBACK

1

B

No

Fresh reader B

None; already resolved

B

T07

AFTER FAIL + savepoint

1

AR1

Yes

ROLLBACK TO → A0; RELEASE → A0

Outer COMMIT

A0

T08

AFTER FAIL

1

AR1

Yes

Observer B

Outer ROLLBACK

B

T09

BEFORE FAIL

2

A1 then A2

Yes

Observer B after each

Diagnostic COMMIT

A2

T10

AFTER FAIL + savepoint

1

AR1

Yes

RELEASE → AR1

Outer ROLLBACK

B

The matrix makes the three rollback scopes visible.

FAIL is the partial-write case: timing determines whether the source row had already happened when failure occurs. ABORT restores the current statement while retaining marker A. ROLLBACK removes the entire explicit transaction. An owned savepoint can rewind candidate-local effects without discarding earlier work, but only when the savepoint existed before those effects and remains an available boundary. SQLite’s trigger, conflict, and savepoint documentation support those scope distinctions.

The comparison with SQLite REPLACE and child-row preservation is useful precisely because it is a different preservation problem. That article asks which related rows survive a successful conflict write. Here the evidence question is which tables retain pending effects after an explicit trigger rejection.

Preserve an evidence record that can contradict the hypothesis

A credible run should retain enough information to falsify the expected matrix.

At minimum, retain:

  • all ten IDs, with no missing or duplicate case;

  • platform.python_version(), sqlite3.sqlite_version, and sqlite_source_id();

  • verified journal_mode;

  • exact installed trigger SQL for each case;

  • every attempt’s exception class, text, extended code, and extended name;

  • exact sorted tuples for outer_work, requests, and counters;

  • Connection.in_transaction at each checkpoint;

  • each read-only observer snapshot;

  • complete recovery sequence, including ROLLBACK TO, RELEASE, COMMIT, or ROLLBACK;

  • final reopened state and comparison with the independent literal oracle.

Cleanup belongs after those measurements. If an assertion fails, the cleanup rollback must not be rewritten into the evidence as though it were the intended case resolution.

A trace callback may supplement the record, but it is not proof that every logged SQL operation persisted. The authoritative evidence in this fixture is database readback plus transaction state at controlled checkpoints.

An interrupted run, missing case, absent trigger SQL, unexpected engine state, or mismatched exception metadata is not a PASS. The appropriate disposition is HOLD.

Choose a repair that matches the authorized unit of work

The engine tells you what happened. Application ownership determines what is acceptable.

Decision

Use when

Prerequisites

REPAIR_TRIGGER_ACTION

Statement rejection is required to erase effects attributable to that statement

Schema owner confirms that statement-level rollback matches the contract; changed trigger is requalified

ROLLBACK_CANDIDATE

Earlier transaction work must remain, but all candidate-local effects must be removed

Savepoint exists before candidate work; caller owns it; transaction is still active; post-rollback tuple verification passes

ROLLBACK_WHOLE_UNIT

Candidate rejection invalidates the complete owned transaction

Caller opened and owns the transaction; discarding earlier work is authorized

HOLD

Evidence, ownership, runtime, trigger DDL, boundary, or resulting state is uncertain

Investigation resolves the unknown before commit or repair

RAISE(ABORT) is a plausible design choice when the contract says a rejected statement should leave no statement-local changes while preserving prior transaction work. It is not permission to rewrite every production trigger. Trigger timing, other trigger bodies, caller expectations, and application error handling must be requalified against the real schema.

A helper also cannot safely say, “on error, roll back everything,” when it does not own the caller’s transaction. That might discard unrelated authorized work.

Nor should a helper assume that because it sees error 1811, a savepoint exists at the correct location. The boundary must be established and owned, not inferred from the failure.

Finally, once T02-, T04-, or T09-like state has been deliberately committed, ordinary rollback cannot reach backward across that commit. Any later compensation is a new database operation with its own authorization and failure modes. There is no universal inverse supplied here.

Assign ownership and requalify changes to the contract

Schema ownership and transaction ownership are related but distinct.

The schema owner owns the trigger’s timing, trigger body, and chosen RAISE action. That owner must decide whether a trigger that rejects a request is allowed to leave its preceding side effects intact.

The backend transaction owner owns whether earlier marker-like work may be preserved or must be abandoned. Only that owner can authorize candidate rollback versus whole-unit rollback.

The release reviewer owns qualification evidence. A release should not be accepted because “SQLite raised the expected exception.” The reviewer needs the complete write-set matrix, transaction flags, observer reads, runtime identity, installed trigger SQL, and recovery sequence.

This distinction separates engine correctness from policy correctness. T02 could behave exactly as SQLite documents and still reveal an unacceptable application contract: a rejected request incremented a counter that the application intended to mean “accepted requests.” T04 could likewise be a perfect demonstration of AFTER FAIL semantics while being an unsuitable production design if a rejected row must never remain pending.

The engine behavior is the mechanism. Acceptance is the application contract.

sqlite-trigger-img-second

A diagnostic commit is especially important to classify correctly. Committing T02, T04, or T09 demonstrates what would become durable under an ordinary SQL commit; it is not a recommendation to accept rejected production work.

Define the changes that require a fresh qualification

Re-run the qualification when any material boundary changes, including:

  • trigger timing, body, or RAISE action;

  • addition or removal of other triggers;

  • candidate statement shape;

  • Python or SQLite runtime selected by release policy;

  • transaction-control policy;

  • savepoint placement;

  • caller ownership;

  • external effects associated with candidate handling.

This fixture does not qualify source-row mutation from BEFORE triggers; SQLite expressly cautions about some such BEFORE behavior. It also does not qualify TEMP triggers, attached databases, arbitrary constraint/error families, crash behavior, power-loss durability, concurrent writers, WAL retry behavior, distributed acknowledgements, RETURNING, UPSERT, REPLACE, ORM flushes, executescript(), foreign-key policy, or multirow visitation order.

The production review questions should therefore be concrete:

What state can remain after the exact trigger rejects the exact statement? Is that state only pending, or has an owner committed it? Which boundary existed before the candidate? Who is authorized to resolve that boundary? Does the intended recovery preserve or remove earlier work correctly? What tuple and transaction evidence will remain for a reviewer? What condition forces HOLD instead of an assumption?

A clean result for this fixture is qualification of this fixture, not permission to generalize across different trigger DDL or transaction owners.

Strengthen database verification through structured practice

Failure-path database engineering improves when teams practice three habits: author the expected state independently, measure all tables that can change, and assign explicit ownership to transaction resolution. A raised exception is only one evidence item. Reliable recovery also requires exact writer state, an independent reader view where useful, a known rollback boundary, and retained evidence that can contradict the hypothesis.

Those habits align with the broader database-administration competencies Refonte Learning currently lists for its Database Administrator Essentials program: database fundamentals, advanced SQL, cloud database administration, optimization, backup and recovery, security, monitoring, practical projects, and personalized mentorship. The published page states a three-month duration, 12–14 hours per week, recommends basic programming knowledge, and requires applicants to be working toward a bachelor’s or higher-level degree. It names MySQL Workbench, Oracle SQL Developer, AWS RDS, Azure SQL, and Google Cloud Spanner, and describes successful-completion certificates plus “Potential Internship” wording rather than guaranteed placement.

Readers can review the Database Administrator Essentials curriculum and prerequisites directly. SQLite instruction, Python sqlite3, this exact RAISE/savepoint laboratory, mentor cadence, guaranteed one-to-one format, internship placement, employer, pay, and duration remain unverified; this article does not represent them as advertised program components or promises.