diff --git a/docs/modules/ROOT/pages/how-to/concurrency.adoc b/docs/modules/ROOT/pages/how-to/concurrency.adoc index 706aa75b..4c4b27c4 100644 --- a/docs/modules/ROOT/pages/how-to/concurrency.adoc +++ b/docs/modules/ROOT/pages/how-to/concurrency.adoc @@ -144,7 +144,7 @@ The check costs on the write side only. A laptop A/B on the native wheel (10 cle [[retry-loop]] === A retry loop for REPEATABLE_READ -`db.transaction()` cannot retry, because a `with` block cannot run twice. This loop is the one the probe used for the last row of the table. +`db.transaction()` cannot retry, because a `with` block cannot run twice. This loop is the one the probe used for the last row of the table. It does not see a commit inside `fn` (a `BATCH n` boundary, or `db.commit()`) and would apply that part again, so use it only for an `fn` that commits nothing itself. `run_in_transaction` refuses such a repeat with xref:how-to/errors.adoc#partial-commit[`PartialCommitError`]. [source,python] ---- diff --git a/docs/modules/ROOT/pages/how-to/errors.adoc b/docs/modules/ROOT/pages/how-to/errors.adoc index fd75f2cd..92ba75b7 100644 --- a/docs/modules/ROOT/pages/how-to/errors.adoc +++ b/docs/modules/ROOT/pages/how-to/errors.adoc @@ -89,6 +89,11 @@ One row for each code. A row with more than one engine exception matches any of |=== | Code | Class | Engine exception | Hint +| `partial_commit` +| `PartialCommitError` +| `TransactionException` +| Part of the work is already committed: check what was applied before you run any of it again, because a rerun of the whole block applies that part a second time. + | `duplicate_key` | `DuplicateKeyError` | `DuplicatedKeyException` @@ -185,7 +190,56 @@ The causes without a subclass (`database_read_only`, `query_not_idempotent`, `mi == Which error to retry -`ConflictError` is the one that a retry can fix: another transaction changed the same data first. Run the whole transaction again, or let `db.run_in_transaction(fn)` do it, as described on xref:how-to/transactions.adoc[Transactions] and xref:how-to/concurrency.adoc[Concurrency, processes and crashes]. A `DuplicateKeyError` is not a conflict: the same statement fails again until the value changes. +`ConflictError` is the one that a retry can fix: another transaction changed the same data first. Run the whole transaction again, or let `db.run_in_transaction(fn)` do it, as described on xref:how-to/transactions.adoc[Transactions] and xref:how-to/concurrency.adoc[Concurrency, processes and crashes]. A `DuplicateKeyError` is not a conflict: the same statement fails again until the value changes. A `PartialCommitError` is a conflict that a retry must not repeat. + +[[partial-commit]] +== A block that already committed part of its work + +A statement with a `BATCH n` boundary, or `db.commit()` followed by `db.begin()` inside the block, stores part of the block's work before the block ends. If the block then loses a conflict, running it again would apply that part twice. So `db.run_in_transaction(fn)` and `with db.transaction():` raise `PartialCommitError` instead of `ConflictError`, and `run_in_transaction` does not call `fn` again, also when it had retries left. Check what is stored, then decide what to run again. + +[source,python] +---- +import threading + +from arcadedb import PartialCommitError + +db.command("sql", "CREATE DOCUMENT TYPE Counter") +with db.transaction(): + db.command("sql", "INSERT INTO Counter SET n = 0") + + +def other_writer(): + with db.transaction(): + db.command("sql", "UPDATE Counter SET n = n + 100") + + +def step(): + db.command("sql", "INSERT INTO Memory SET key = 'b'") + db.commit() # the new record is stored from here on + db.begin() + db.command("sql", "UPDATE Counter SET n = n + 1") + writer = threading.Thread(target=other_writer) + writer.start() + writer.join() # it commits first, so the commit of this block conflicts + + +try: + db.run_in_transaction(step) +except PartialCommitError as e: + print(e.code) + stored = db.query("sql", "SELECT count(*) AS c FROM Memory WHERE key = 'b'") + print(stored.first().get("c")) +---- + +[source,text] +---- +partial_commit +1 +---- + +* The error is not a `ConflictError`. The conflict is its `__context__`, not its `__cause__`, so a retry loop that follows the cause chain does not find it, and an outer `run_in_transaction` does not repeat the block either. +* A `DuplicateKeyError` after such a commit keeps its class, and the block is not run again. +* Engine 26.12.1 refuses the same case in its own retry loops, a `COMMIT RETRY` block of a SQL script for example, with a `TransactionException`. When it reaches Python as an `ArcadeDBError`, it has the class and the code above. `e.cause` is that exception's name, and `None` when the packages raise the error themselves. An older engine raises the conflict from those loops. == What differs between the packages diff --git a/docs/modules/ROOT/pages/how-to/transactions.adoc b/docs/modules/ROOT/pages/how-to/transactions.adoc index 1ef1a220..f683dbad 100644 --- a/docs/modules/ROOT/pages/how-to/transactions.adoc +++ b/docs/modules/ROOT/pages/how-to/transactions.adoc @@ -365,6 +365,8 @@ print(db.run_in_transaction(add_account)) added ---- +A repeat is safe only when the failed attempt left nothing behind. A statement with a `BATCH n` boundary, or `db.commit()` followed by `db.begin()` inside the block, stores part of the work. When such a block loses a conflict, `run_in_transaction` does not call `fn` again and raises `PartialCommitError`, not `ConflictError`, on the last attempt too. A `with db.transaction():` block raises the same error in this case. Check what is stored before you run any of it again: see xref:how-to/errors.adoc#partial-commit[A block that already committed part of its work]. + [[graph-batch]] == GraphBatch inside a transaction diff --git a/docs/modules/ROOT/pages/upgrading.adoc b/docs/modules/ROOT/pages/upgrading.adoc index 2a77bfa3..95fe8029 100644 --- a/docs/modules/ROOT/pages/upgrading.adoc +++ b/docs/modules/ROOT/pages/upgrading.adoc @@ -8,7 +8,7 @@ ifdef::env-github[] :jvm-pkg-name: arcadedb-jvm endif::[] -// Sources: the pull requests ArcadeData/arcadedb-python #479 to #483, and the changes of issues #454 and #445. Pinned by tests/test_auto_transaction_default.py, tests/test_error_codes_table.py, tests/test_error_codes_parity.py, tests/test_lazy_import.py, tests/test_cross_wheel_golden.py and tests/test_insert_many_integer_types.py. +// Sources: the pull requests ArcadeData/arcadedb-python #479 to #483, and the changes of issues #454, #445 and #504. Pinned by tests/test_run_in_transaction_partial_commit.py, tests/test_auto_transaction_default.py, tests/test_error_codes_table.py, tests/test_error_codes_parity.py, tests/test_lazy_import.py, tests/test_cross_wheel_golden.py and tests/test_insert_many_integer_types.py. Read this page before you move a program from 26.11.1, or from one of its post releases, to 26.12.1. It covers both packages, `{native-pkg-name}` and `{jvm-pkg-name}`. The changes of the engine itself are listed with the https://github.com/ArcadeData/arcadedb/releases[releases of ArcadeDB]. @@ -45,6 +45,15 @@ Before, `{native-pkg-name}` wrote every character outside ASCII as a `\u` escape Before, `{native-pkg-name}` stored every whole number that `insert_many` wrote as a `Long`. Now it stores an `Integer` when the number fits 32 bits, also inside a list or a dict, and a `Long` beyond that, as `{jvm-pkg-name}` does. A property that the type declares keeps its declared type, the values that Python reads back are the same, and records that are already stored do not change. Code that asks for the stored type, for example with the SQL method `type()`, can see `INTEGER` where it saw `LONG`. See xref:how-to/bulk-loads.adoc[Bulk loads and commit size]. +=== A conflict after a block committed part of its work raises `PartialCommitError` + +Before, `db.run_in_transaction(fn)` and `with db.transaction():` raised `ConflictError` when a block lost a conflict after a `BATCH n` boundary, or a `commit()` inside it, had stored part of its work. The hint said to run the transaction again, which applied that part a second time. Now they raise `PartialCommitError` with the code `partial_commit`, which is not a `ConflictError`. + +* Code that catches `ConflictError` to retry no longer catches this case. Catch `PartialCommitError`, check what is stored, and decide what to run again. +* A block that committed nothing behaves as before. + +See xref:how-to/errors.adoc#partial-commit[A block that already committed part of its work]. + === Engine 26.12.1 The engine that the 26.12.1 packages carry changes some behaviour that the other pages describe: diff --git a/native/src/main/java/org/humemai/nativelib/ArcadeNative.java b/native/src/main/java/org/humemai/nativelib/ArcadeNative.java index c8220887..585b6d81 100644 --- a/native/src/main/java/org/humemai/nativelib/ArcadeNative.java +++ b/native/src/main/java/org/humemai/nativelib/ArcadeNative.java @@ -37,6 +37,7 @@ import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.charset.StandardCharsets; +import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; @@ -49,6 +50,13 @@ public final class ArcadeNative { private static final Map SERVERS = new ConcurrentHashMap<>(); static final AtomicLong IDS = new AtomicLong(1); + /** + * Per thread, the context that a begin inside a transaction pushed, by database handle and depth ({@link #blockKey}). A commit + * pops that context, so its commit count, which tells whether the block committed part of its work + * (ArcadeData/arcadedb-python#504), can only be read from here. Written by op 4 of arcadedb_n_tx, read and removed by op 5. + */ + private static final ThreadLocal> NESTED_BLOCKS = ThreadLocal.withInitial(HashMap::new); + static { // The image carries no GraalVM polyglot languages by design, so the engine's polyglot registration can only find none and // would log "GraalVM Polyglot Engine: no languages found" at WARNING in every process (#477). Turn the engine off before the @@ -160,6 +168,7 @@ public static CCharPointer close(final IsolateThread thread, final long h, final else db.close(); DBS.remove(h); + NESTED_BLOCKS.get().keySet().removeIf(key -> key >>> 32 == h); return OK(); } catch (final Throwable t) { return err(t); @@ -186,7 +195,9 @@ public static CCharPointer info(final IsolateThread thread, final long h) { } /** - * op 0 begin, 1 commit, 2 rollback, 3 mark. Returns the transaction state after the call as one non-negative long: bit 0 is + * op 0 begin, 1 commit, 2 rollback, 3 mark, 4 mark and remember the current context for its depth, 5 | depth << 8 the commit + * count of the context remembered for that depth, in the commit bits of the result and with the other bits 0 (the entry is + * dropped; 0 when there is none). Ops 0 to 4 return the transaction state after the call as one non-negative long: bit 0 is * isTransactionActive, bits 1 to 31 the nesting depth, bits 32 to 62 the low 31 bits of the commit count of the thread's * transaction context (callers compare two counts for equality). -1 on error: the error text is then read with * arcadedb_n_last_error on the same thread, as for arcadedb_n_cmd. No reply text, so no malloc, no arcadedb_free and no JSON @@ -196,10 +207,18 @@ public static CCharPointer info(final IsolateThread thread, final long h) { public static long tx(final IsolateThread thread, final long h, final int op) { try { final Database db = db(h); - switch (op) { + switch (op & 0xFF) { case 0 -> db.begin(); case 1 -> db.commit(); case 2 -> db.rollback(); + case 4 -> { + if (db instanceof DatabaseInternal internal) + NESTED_BLOCKS.get().put(blockKey(h, (txState(db) >>> 1) & 0x7FFFFFFFL), internal.getTransactionIfExists()); + } + case 5 -> { + final TransactionContext block = NESTED_BLOCKS.get().remove(blockKey(h, op >>> 8)); + return block == null ? 0L : (block.getCommitCount() & 0x7FFFFFFFL) << 32; + } default -> { } } @@ -210,6 +229,10 @@ public static long tx(final IsolateThread thread, final long h, final int op) { } } + private static long blockKey(final long h, final long depth) { + return h << 32 | depth; + } + private static long txState(final Database db) { long depth = 0; long commits = 0; diff --git a/src/arcadedb/__init__.py b/src/arcadedb/__init__.py index 55c362d0..609be288 100644 --- a/src/arcadedb/__init__.py +++ b/src/arcadedb/__init__.py @@ -82,6 +82,7 @@ def __getattr__(name: str) -> str: DatabaseLockedError, DatabaseNotFoundError, DuplicateKeyError, + PartialCommitError, QuerySyntaxError, QueryTimeoutError, RecordNotFoundError, @@ -159,6 +160,7 @@ def __getattr__(name: str) -> str: "DatabaseLockedError", "DatabaseNotFoundError", "DuplicateKeyError", + "PartialCommitError", "QuerySyntaxError", "QueryTimeoutError", "RecordNotFoundError", diff --git a/src/arcadedb/_native/database.py b/src/arcadedb/_native/database.py index 3e0b6699..917f2b3f 100644 --- a/src/arcadedb/_native/database.py +++ b/src/arcadedb/_native/database.py @@ -12,7 +12,7 @@ from .. import _columnar from .._open_or_create import open_or_create from .._params import refuse_surplus_positionals -from ..exceptions import ArcadeDBError +from ..exceptions import ArcadeDBError, _partial_commit_error from ..transactions import TransactionContext from ..type_conversion import bulk_row_ok, json_bulk_dumps_tagged from . import interrupts, lib, needs_jvm @@ -69,6 +69,18 @@ def _error(prefix: str, reply: dict) -> ArcadeDBError: ) # a Ctrl-C in a Python function is a KeyboardInterrupt chained from this error +def _is_conflict(failure) -> bool: + """Whether a conflict that a rerun could absorb is ``failure`` or sits in its cause chain, as ``_retry_verdict`` looks for one.""" + seen = set() + while failure is not None and id(failure) not in seen: + seen.add(id(failure)) + reply = getattr(failure, "native", None) + if reply and reply.get("retry"): + return reply["retry"] == "need_retry" + failure = failure.__cause__ + return False + + def _read_error(reply: dict) -> ArcadeDBError: chain = reply.get("chain") or [] exc = ArcadeDBError._classified( @@ -92,6 +104,12 @@ def _call(prefix: str, name: str, *args) -> dict: # bits: callers compare two of them for equality). Callers read the fields inline: ``state & 1``, ``(state >> 1) & 0x7FFFFFFF``, # ``state >> 32``. -1 is an error: its text, the ``{"ok":false,...}`` reply of every other entry point, is ``lib.last_error()``. +# The two operations beside begin (0), commit (1), rollback (2) and mark (3), for a block that begins inside a caller's transaction +_REMEMBER_NESTED = 4 # remember the context begin() pushed, for its depth +_NESTED_COMMITS = ( + 5 # ``| depth << 8``: that context's commit count, in the ``commits`` field +) + def _first_row(database, reply: dict): """``NativeResultSet(database, reply).first()`` for a reply that holds the whole result: the first row as a ``NativeResult``, with no @@ -1005,12 +1023,51 @@ def is_transaction_active(self) -> bool: return bool(self._tx_state(3, "Failed to check transaction status") & 1) def _transaction_stack_mark(self): + return self._transaction_marks()[0] + + def _transaction_marks(self): + """The stack mark ``(active, depth)``, and the commit count of the thread's transaction context, in one crossing.""" state = self._tx_state(3, "Failed to read the transaction state") - return bool(state & 1), (state >> 1) & 0x7FFFFFFF + return (bool(state & 1), (state >> 1) & 0x7FFFFFFF), state >> 32 - def _transaction_commit_mark(self): - """The commit count of the current transaction (the witness that a BATCH boundary published part of its work).""" - return self._tx_state(3, "Failed to read the transaction state") >> 32 + def _commit_witness(self, mark, commits): + """What tells later whether a block committed part of its work, taken right after its begin(): ``(depth, commits)``. + + Outside a transaction, begin() reuses the thread's context: ``(0, commits)``, its commit count at the start. Inside one, + begin() pushed a context of its own, which a commit pops, so the library is asked to remember it (one more crossing) + and ``depth`` names it. + """ + if not mark[0]: + return 0, commits + state = self._tx_state(_REMEMBER_NESTED, "Failed to read the transaction state") + return (state >> 1) & 0x7FFFFFFF, 0 + + def _partially_committed(self, witness, state=None) -> bool: + """Whether the block of ``witness`` published part of its work. ``state``: the transaction state after the unwind, when + the caller has it. Only the READ may fail quietly (no witness: not partial, as before the witness existed). + """ + depth, commits_at_start = witness + try: + if depth: + state = self._tx_state( + _NESTED_COMMITS | depth << 8, "Failed to read the transaction state" + ) + elif state is None: + state = self._tx_state(3, "Failed to read the transaction state") + except ArcadeDBError: + return False + return state >> 32 != commits_at_start + + def _partial_commit_refusal(self, failure, witness, block, state=None): + """The ``PartialCommitError`` to raise instead of ``failure``: a conflict of a block that committed part of its work. + + None for every other failure, and for a block that committed nothing. + """ + if witness is None or not _is_conflict(failure): + return None + if not self._partially_committed(witness, state): + return None + return _partial_commit_error(block, failure) def _unwind_opened_since(self, mark): """Roll back every level opened since ``mark``, and no other; returns ``(state, first_error)``. @@ -1051,14 +1108,15 @@ def run_in_transaction(self, fn, retries: int = 12, backoff_s: float = 0.005): """``fn`` inside a transaction, retried on NeedRetry conflicts (see the JPype ``Database.run_in_transaction``). Three crossings on the happy path: the mark before begin (what this call owns), begin (its reply is the commit-count - witness) and commit. The mark must stay before begin: a mark read after it would count the level begin pushed as the caller's. + witness) and commit; inside a caller's transaction, one more for the witness. The mark must stay before begin: a mark + read after it would count the level begin pushed as the caller's. """ duplicated_key_retried = False for attempt in range(retries + 1): mark = self._transaction_stack_mark() - commits_at_start = None + witness = None try: - commits_at_start = self._begin_state() >> 32 + witness = self._commit_witness(mark, self._begin_state() >> 32) result = fn() self.commit() return result @@ -1068,7 +1126,16 @@ def run_in_transaction(self, fn, retries: int = 12, backoff_s: float = 0.005): state, _ = self._unwind_opened_since(mark) except Exception: # nosec B110 pass - if attempt >= retries or not isinstance(e, Exception): + if not isinstance(e, Exception): + raise + # the rollback above cannot take back what a BATCH boundary or a commit() inside fn already made durable, and a + # replay would apply it twice: such a conflict is not retryable for anyone, on the last attempt too (#504) + refusal = self._partial_commit_refusal( + e, witness, "run_in_transaction block", state + ) + if refusal is not None: + raise refusal + if attempt >= retries: raise reply = getattr(e, "native", None) or {} kind = reply.get("retry") @@ -1078,19 +1145,10 @@ def run_in_transaction(self, fn, retries: int = 12, backoff_s: float = 0.005): if duplicated_key_retried: raise duplicated_key_retried = True - if commits_at_start is not None: - # the rollback above cannot take back what a BATCH boundary or a commit() inside the block already made - # durable, and a replay would apply it twice. Only the READ of the witness may fail quietly (no witness: - # retry, as before); the raise sits outside that try, or its own except would swallow it. - try: - commits_now = ( - state >> 32 - if state is not None - else self._transaction_commit_mark() - ) - except ArcadeDBError: - commits_now = commits_at_start - if commits_now != commits_at_start: + # a duplicated key after a commit is raised as it is, as the engine does, and not replayed + if witness is not None and self._partially_committed( + witness, state + ): raise _time.sleep( max(backoff_s * (attempt + 1), reply.get("retry_ms", 0) / 1000.0) diff --git a/src/arcadedb/_native/lib.py b/src/arcadedb/_native/lib.py index 90ca6911..92b72105 100644 --- a/src/arcadedb/_native/lib.py +++ b/src/arcadedb/_native/lib.py @@ -545,7 +545,8 @@ def cmd(handle, flags, language, command, params, buf, count, first) -> int: def tx(handle, op) -> int: """``arcadedb_n_tx``: op 0 begin, 1 commit, 2 rollback, 3 mark. Returns the transaction state after the call as one int (bit 0 ``active``, bits 1 to 31 ``depth``, bits 32 to 62 ``commits``, as ``ArcadeNative.tx`` writes it), or -1 for an error (read it - with :func:`last_error`). One foreign call: no reply text to copy, free or decode. + with :func:`last_error`). One foreign call: no reply text to copy, free or decode. Ops 4 and 5 remember and read the context + of a block that begins inside a transaction (see ``ArcadeNative.tx``). """ lib = _lib or _load() t = _local.__dict__.get("thread") diff --git a/src/arcadedb/core.py b/src/arcadedb/core.py index 2bf4254b..12f477cb 100644 --- a/src/arcadedb/core.py +++ b/src/arcadedb/core.py @@ -31,7 +31,7 @@ raise_pending_interrupt, register_event, ) -from .exceptions import ArcadeDBError, _retry_verdict +from .exceptions import ArcadeDBError, _partial_commit_error, _retry_verdict from .graph import Document, Edge, Vertex from .graph_batch import GraphBatch from .importer import ImportResult @@ -99,6 +99,9 @@ def _warn_no_commit_witness(what): _JArray = jpype.JArray +# The witness of a ``with db.transaction():`` block whose begin() reused the thread's transaction context (see _commit_witness) +_REUSED_CONTEXT = object() + # Resolved on first use, once the JVM is up (see _db_calls and _object_array). _DB_CALLS = None _OBJECT_ARRAY = None @@ -716,10 +719,13 @@ def run_in_transaction( genuine duplicate fails the same way every time, and one retry covers the duplicate raised by racing a concurrent commit. A block that already made part of its work durable (a statement with a ``BATCH`` - boundary) is never re-run: the conflict is raised, because a replay - would apply that part twice. The ``with db.transaction():`` context - manager cannot retry (a ``with`` block can't be re-entered), so use - this for contended multi-threaded writes. + boundary, or ``commit()`` and ``begin()`` inside ``fn``) is never + re-run, because a replay would apply that part twice: a conflict is + raised as ``PartialCommitError``, which is not a ``ConflictError``, on + the last attempt too (a ``DuplicatedKeyError`` is raised as it is). + The ``with db.transaction():`` context manager raises the same error, + but cannot retry (a ``with`` block can't be re-entered), so use this + for contended multi-threaded writes. A refusal's wait is capped by ``arcadedb.network.retryAfterMaxWait`` per attempt, so a call can block for up to ``retries`` times that cap @@ -770,7 +776,18 @@ def run_in_transaction( self._end_transactions_opened_since(mark) except Exception: # nosec B110 - best-effort rollback before retry pass - if attempt >= retries or not isinstance(e, Exception): + if not isinstance(e, Exception): + raise + # #7916, #504: the rollback above cannot take back what a BATCH + # boundary or a commit() inside fn already committed, and a replay + # would apply it twice. A conflict after such a commit is not + # retryable for anyone, on the last attempt too. + refusal = self._partial_commit_refusal( + e, (tx_at_start, commits_at_start), "run_in_transaction block" + ) + if refusal is not None: + raise refusal + if attempt >= retries: raise # By Java TYPE, as LocalDatabase.transaction() decides. The # message used to be searched for two class names, so every @@ -784,9 +801,8 @@ def run_in_transaction( if duplicated_key_retried: raise duplicated_key_retried = True - # #7916: the rollback above cannot take back what a BATCH - # boundary already committed, and a replay would apply it twice - # and report clean success. + # a duplicated key after a commit is raised as it is, as the engine + # does: nobody is told to retry it, and it is not replayed here if self._partially_committed(tx_at_start, commits_at_start): raise _time.sleep(max(backoff_s * (attempt + 1), retry_after_ms / 1000.0)) @@ -799,17 +815,56 @@ def _transaction_stack_mark(self): The pair is what _end_transactions_opened_since needs to tell the levels a begin() pushed from the ones the caller already held. """ + return self._transaction_marks()[0] + + def _transaction_marks(self): + """The stack mark ``(active, depth)``, and the commit count of the thread's transaction context (its low 31 bits).""" calls = _db_calls() if calls is not None: - # both numbers in ONE crossing: this runs before every begin() of + # all three numbers in ONE crossing: this runs before every begin() of # ``with db.transaction()`` and of run_in_transaction self._check_not_closed() try: packed = int(calls.stackMark(self._java_db)) except Exception as e: raise ArcadeDBError(f"Failed to check transaction status: {e}") from e - return bool(packed & 1), packed >> 1 - return self.is_transaction_active(), self._java_db.getNestedTransactions() + return (bool(packed & 1), (packed >> 1) & 0x7FFFFFFF), packed >> 32 + mark = self.is_transaction_active(), self._java_db.getNestedTransactions() + return mark, self._transaction_commit_mark()[1] & 0x7FFFFFFF + + def _commit_witness(self, mark, commits): + """What ``with db.transaction():`` compares against to see a commit inside the block, taken right after its begin(). + + Outside a transaction, begin() reuses the thread's context, so the commit count read with the mark is its count at the + start and nothing is asked here (``_REUSED_CONTEXT``: the context is looked up when the block has failed). Inside one, + begin() pushed a context of its own, which a commit pops: it is held from here on. + """ + if mark[0]: + return self._transaction_commit_mark() + return _REUSED_CONTEXT, commits + + def _partial_commit_refusal(self, failure, witness, block): + """The ``PartialCommitError`` to raise instead of ``failure``: a conflict of a block that committed part of its work. + + None for every other failure, and for a block that committed nothing. + """ + if _retry_verdict(failure)[0] != "need_retry": + return None + tx_at_start, commits_at_start = witness + if tx_at_start is _REUSED_CONTEXT: + try: + tx_at_start = self._java_db.getTransactionIfExists() + partial = ( + tx_at_start is not None + and int(tx_at_start.getCommitCount()) & 0x7FFFFFFF + != commits_at_start + ) + except Exception: # no witness: the conflict is raised as it is + _warn_no_commit_witness("count") + return None + else: + partial = self._partially_committed(tx_at_start, commits_at_start) + return _partial_commit_error(block, failure) if partial else None def _end_transactions_opened_since(self, mark): """Roll back every transaction level opened since ``mark``, and no other. diff --git a/src/arcadedb/exceptions.py b/src/arcadedb/exceptions.py index d36697da..b081a866 100644 --- a/src/arcadedb/exceptions.py +++ b/src/arcadedb/exceptions.py @@ -334,6 +334,16 @@ class ConflictError(ArcadeDBError): code = "conflict" +class PartialCommitError(ArcadeDBError): + """A block lost a conflict after part of its work was committed, so running it again applies that part twice (``partial_commit``). + + Not a :class:`ConflictError`, and the conflict is not its ``__cause__``, so that no retry loop runs the block again. When + ``run_in_transaction`` or ``with db.transaction():`` raise it, the conflict is its ``__context__``. + """ + + code = "partial_commit" + + class SchemaError(ArcadeDBError): """A type, property or index is missing, exists already, or refuses the change (``type_not_found``, ``already_exists``, ``schema``).""" @@ -384,6 +394,16 @@ class _Rule(NamedTuple): # produces, collected by running both builds (tests/test_error_codes_table.py holds a literal for every row). A row with a # ``message`` and no ``java`` is for a failure that the Python layer raises itself or that one build words differently. _RULES = ( + # first: the engine wraps this refusal in a timeout when a COMMIT RETRY block ran out of time, and the half that is committed + # matters more than the deadline + _Rule( + "partial_commit", + PartialCommitError, + "Part of the work is already committed: check what was applied before you run any of it again, because a rerun of the " + "whole block applies that part a second time.", + java=(_E + "TransactionException",), + message=re.compile(r"committed part of its work before failing"), + ), _Rule( "duplicate_key", DuplicateKeyError, @@ -549,6 +569,32 @@ class _Rule(NamedTuple): ) +def _partial_commit_error(block, conflict): + """The ``PartialCommitError`` for a ``block`` that lost ``conflict`` after it had committed part of its work (#504). + + The engine's own retry loops raise a ``TransactionException`` with this wording for the same refusal (engine 26.12.1), so + ``_RULES`` gives the two the same class and code. The caller raises the result while it handles ``conflict`` and without + ``from``: the conflict stays visible as ``__context__``, and nothing that follows the cause chain to decide on a retry + (``_retry_verdict``) finds it. + """ + chain = _java_chain_of(conflict) + if chain: + conflicts = _RULE_OF_CODE["conflict"].java + name, message = next( + (link for link in chain if link[0] in conflicts), chain[-1] + ) + else: + name, message = type(conflict).__name__, str(conflict) + text = ( + f"{block} committed part of its work before failing with {name.rsplit('.', 1)[-1]} ({message}). It is not retried, " + "because a replay would apply the already committed part a second time: check what was applied before running it again" + ) + error = PartialCommitError(text) + # what a wrapper that re-raises this error classifies it by: the exception the engine raises for the same refusal + error._chain = ((_E + "TransactionException", text),) + return error + + def _classify(text, chain=()): """``(rule, cause)`` for an error with this ``text`` and Java ``chain``: the first matching row, or ``(None, root cause)``.""" names = [name for name, _ in chain] or _CLASS_IN_TEXT.findall(text) diff --git a/src/arcadedb/transactions.py b/src/arcadedb/transactions.py index bfa43a62..aab8757e 100644 --- a/src/arcadedb/transactions.py +++ b/src/arcadedb/transactions.py @@ -17,16 +17,19 @@ class TransactionContext: def __init__(self, database: "Database"): self.database = database self.started = False + self._witness = None def __enter__(self) -> "TransactionContext": # The levels the caller already holds are not ours to roll back: begin() inside a caller's transaction pushes a # nested level, so ownership is decided by the stack before the call, not by whether begin() returned (#9970) - mark = self.database._transaction_stack_mark() + mark, commits = self.database._transaction_marks() try: # begin() inside the try: an interrupt landing right after it must still reach the rollback, # because an exception out of __enter__ means __exit__ never runs self.database.begin() self.started = True + # what tells at the end whether the block committed part of its work (#504) + self._witness = self.database._commit_witness(mark, commits) return self except BaseException: self.started = False @@ -42,8 +45,26 @@ def __exit__( exc_val: Optional[BaseException], exc_tb: Optional[TracebackType], ) -> None: - if self.started: - if exc_type is None: + if not self.started: + return + if exc_type is None: + try: self.database.commit() - else: - self.database.rollback() + except Exception as e: + self._refuse_a_rerun(e) + raise + else: + self.database.rollback() + if isinstance(exc_val, Exception): + self._refuse_a_rerun(exc_val) + + def _refuse_a_rerun(self, failure: Exception) -> None: + """Raise ``PartialCommitError`` instead of ``failure`` when it is a conflict and part of the block is committed. + + A conflict tells the caller to run the whole transaction again, which would apply the committed part twice (#504). + """ + refusal = self.database._partial_commit_refusal( + failure, self._witness, "Transaction block" + ) + if refusal is not None: + raise refusal diff --git a/src/java/com/arcadedb/python/DbCalls.java b/src/java/com/arcadedb/python/DbCalls.java index ec0c03e4..fddf2981 100644 --- a/src/java/com/arcadedb/python/DbCalls.java +++ b/src/java/com/arcadedb/python/DbCalls.java @@ -14,7 +14,9 @@ package com.arcadedb.python; import com.arcadedb.database.Database; +import com.arcadedb.database.DatabaseInternal; import com.arcadedb.database.Record; +import com.arcadedb.database.TransactionContext; import com.arcadedb.index.IndexCursor; import com.arcadedb.query.sql.executor.ResultSet; @@ -92,11 +94,15 @@ public static Record lookupFirstKeys(final Database db, final String type, final } /** - * The transaction stack of {@code db} as one number, {@code nestedTransactions * 2 + (active ? 1 : 0)}: the - * {@code isTransactionActive()} and {@code getNestedTransactions()} of the mark {@code run_in_transaction} and - * {@code with db.transaction()} take before {@code begin()} (#9970, #9813), in one crossing instead of two. + * The transaction state of {@code db} as one number: bit 0 is {@code isTransactionActive()}, bits 1 to 31 + * {@code getNestedTransactions()} and bits 32 to 62 the commit count of the thread's transaction context (its low 31 bits). + * The first two are the mark {@code run_in_transaction} and {@code with db.transaction()} take before {@code begin()} + * (#9970, #9813); the count tells a {@code with} block whether it committed part of its work (ArcadeData/arcadedb-python#504). + * One crossing for all three. */ public static long stackMark(final Database db) { - return ((long) db.getNestedTransactions() << 1) | (db.isTransactionActive() ? 1L : 0L); + final TransactionContext tx = ((DatabaseInternal) db).getTransactionIfExists(); + final long commits = tx == null ? 0L : tx.getCommitCount(); + return (commits & 0x7FFFFFFFL) << 32 | (db.getNestedTransactions() & 0x7FFFFFFFL) << 1 | (db.isTransactionActive() ? 1L : 0L); } } diff --git a/tests/test_docs_errors_page.py b/tests/test_docs_errors_page.py index 53bd7938..20c4beb5 100644 --- a/tests/test_docs_errors_page.py +++ b/tests/test_docs_errors_page.py @@ -39,8 +39,8 @@ def _blocks(): def test_the_page_has_its_blocks(): blocks = _blocks() - assert len(blocks) == 3 - assert sum(1 for _, out in blocks if out is not None) == 3 + assert len(blocks) == 4 + assert sum(1 for _, out in blocks if out is not None) == 4 def test_every_block_runs_in_order_and_prints_what_the_page_says(temp_db): diff --git a/tests/test_error_codes_parity.py b/tests/test_error_codes_parity.py index 548fb327..a4ee57d7 100644 --- a/tests/test_error_codes_parity.py +++ b/tests/test_error_codes_parity.py @@ -191,6 +191,23 @@ def slow_writer(): raise errors[0] +def conflict_after_a_commit_in_the_block(db): + _insert(db) + + def other_writer(): + with db.transaction(): + db.command("sql", "UPDATE T SET k = 2 WHERE id = 1") + + with db.transaction(): + db.command("sql", "INSERT INTO T SET id = 2") + db.commit() # stored from here on: the block must not be run again + db.begin() + db.command("sql", "UPDATE T SET k = 3 WHERE id = 1") + writer = threading.Thread(target=other_writer) + writer.start() + writer.join(timeout=60) + + def unknown_type_in_query(db): db.query("sql", "SELECT FROM Nope").to_list() @@ -406,6 +423,13 @@ def unknown_function(db): "timeout", E + "TimeoutException", ), + # the packages raise this one themselves, so no Java class decides it + ( + on_a_database(conflict_after_a_commit_in_the_block), + "PartialCommitError", + "partial_commit", + None, + ), ( on_a_database(conflict_of_two_transactions), "ConflictError", diff --git a/tests/test_error_codes_table.py b/tests/test_error_codes_table.py index 1f8e86e5..e9c3d90c 100644 --- a/tests/test_error_codes_table.py +++ b/tests/test_error_codes_table.py @@ -21,6 +21,33 @@ # (id, text of the error, Java chain (outermost first), expected class, expected code, expected cause) CASES = [ + ( + "partial_commit", + "Command failed: com.arcadedb.exception.TransactionException: COMMIT RETRY block committed part of its work before failing with ConcurrentModificationException (changed). It is not retried", + [ + ( + E + "TransactionException", + "COMMIT RETRY block committed part of its work before failing with ConcurrentModificationException (changed). It is not retried", + ) + ], + "PartialCommitError", + "partial_commit", + E + "TransactionException", + ), + ( + "partial_commit_inside_a_timeout", + "Command failed: com.arcadedb.exception.TimeoutException: COMMIT RETRY gave up after 1 of 5 attempts", + [ + (E + "TimeoutException", "COMMIT RETRY gave up after 1 of 5 attempts"), + ( + E + "TransactionException", + "COMMIT RETRY block committed part of its work before failing with ConcurrentModificationException (changed). It is not retried", + ), + ], + "PartialCommitError", + "partial_commit", + E + "TransactionException", + ), ( "duplicate_key", "Command failed: com.arcadedb.exception.DuplicatedKeyException: Duplicated key [1] found on index 'T[id]' already assigned to record #1:0", @@ -483,6 +510,7 @@ def test_the_subclasses_are_public_and_under_the_base_class(): "DatabaseLockedError", "DatabaseNotFoundError", "DuplicateKeyError", + "PartialCommitError", "QuerySyntaxError", "QueryTimeoutError", "RecordNotFoundError", @@ -523,6 +551,34 @@ def test_a_wrapper_around_a_classified_error_keeps_the_class_and_does_not_repeat assert outer.args == ("Failed to commit transaction: " + text,) +def test_the_refusal_of_a_rerun_is_not_a_conflict_and_a_wrapper_keeps_its_class(): + """``run_in_transaction`` builds this error itself (#504): it names the conflict, and no class name in it decides again.""" + message = "Concurrent modification on page 0" + conflict = ArcadeDBError._classified( + f"Failed to commit transaction: {E}ConcurrentModificationException: {message}", + [(E + "ConcurrentModificationException", message)], + ) + refusal = exceptions._partial_commit_error("run_in_transaction block", conflict) + assert (type(refusal).__name__, refusal.code, refusal.cause) == ( + "PartialCommitError", + "partial_commit", + None, + ) + assert str(refusal).startswith(f"[partial_commit] {refusal.hint} ") + assert ( + "run_in_transaction block committed part of its work before failing with ConcurrentModificationException " + f"({message})" + ) in str(refusal) + assert not isinstance(refusal, exceptions.ConflictError) + try: + try: + raise refusal + except ArcadeDBError as e: + raise ArcadeDBError(f"Failed to store the step: {e}") from e + except exceptions.PartialCommitError as outer: + assert str(outer).count("[partial_commit]") == 1 + + def test_a_statement_that_a_syntax_error_echoes_does_not_decide_the_code(): text = "Query failed: com.arcadedb.exception.CommandSQLParsingException: SQL syntax error at line 1: SELECT 'record not found' FROM" error = ArcadeDBError._classified( diff --git a/tests/test_native_tx_crossings.py b/tests/test_native_tx_crossings.py index d3b1dee6..d90bb703 100644 --- a/tests/test_native_tx_crossings.py +++ b/tests/test_native_tx_crossings.py @@ -24,7 +24,14 @@ from arcadedb import ArcadeDBError from arcadedb._native import lib -_OPS = {0: "begin", 1: "commit", 2: "rollback", 3: "mark"} +_OPS = { + 0: "begin", + 1: "commit", + 2: "rollback", + 3: "mark", + 4: "remember", + 5: "nested-commits", +} _DEPTH_MASK = 0x7FFFFFFF @@ -42,7 +49,7 @@ def __init__(self, monkeypatch): real_call = lib.call def counting_tx(handle, op): - self.calls.append(_OPS[op]) + self.calls.append(_OPS[op & 0xFF]) return real_tx(handle, op) def counting_call(name, *args): @@ -242,6 +249,33 @@ def test_a_transaction_never_reads_a_reply_text(db, monkeypatch): assert taken == [] +def test_a_nested_block_costs_one_crossing_for_its_witness(db, crossings): + # a block inside a transaction has a context of its own, which its commit pops: the library remembers it (#504) + with db.transaction(): + crossings.reset() + db.run_in_transaction(lambda: None) + with db.transaction(): + pass + assert crossings.calls[:-1] == ["mark", "begin", "remember", "commit"] * 2 + + +def test_a_nested_conflict_reads_the_witness_once(db, crossings): + attempts = [] + + def fn(): + attempts.append(1) + if len(attempts) == 1: + raise _need_retry() + + with db.transaction(): + crossings.reset() + db.run_in_transaction(fn, backoff_s=0) + assert crossings.calls == [ + *["mark", "begin", "remember", "mark", "rollback", "nested-commits"], + *["mark", "begin", "remember", "commit"], + ] + + # -- what the marks are for: the same results at the lower count diff --git a/tests/test_run_in_transaction_partial_commit.py b/tests/test_run_in_transaction_partial_commit.py index 1295846e..c87f6173 100644 --- a/tests/test_run_in_transaction_partial_commit.py +++ b/tests/test_run_in_transaction_partial_commit.py @@ -1,10 +1,13 @@ """ -``Database.run_in_transaction`` never replays a block that already committed part of its work (#7916), on both wheels. +A block that already committed part of its work is never replayed, and its error says so, on both wheels +(#7916, ArcadeData/arcadedb-python#504). A statement with a ``BATCH n`` boundary, or a ``commit()`` inside the block, makes part of the block's work durable. When the block -then hits a retryable conflict, the rollback cannot take that part back, and a replay would apply it twice and report clean success. -The conflict has to be raised instead. The conflict here is a real one (a second thread commits to a record the block also wrote), so -the same test runs against the JPype wheel and the native wheel, and it needs neither a Java class nor a fabricated error. +then loses a conflict, the rollback cannot take that part back, and a replay would apply it twice and report clean success. So +``run_in_transaction`` and ``with db.transaction():`` raise ``PartialCommitError``: not a ``ConflictError``, whose hint says to run +the transaction again, and with the conflict as its ``__context__``, not as its ``__cause__``, so that no retry loop finds it. The +conflict here is a real one (a second thread commits to a record the block also wrote), so the same test runs against the JPype +wheel and the native wheel, and it needs neither a Java class nor a fabricated error. The native wheel's guard once sat in a ``try`` whose own ``except ArcadeDBError: pass`` swallowed the ``raise`` it was written to make, so a native block that had committed part of its work was replayed. @@ -15,7 +18,7 @@ import pytest import arcadedb as arcadedb -from arcadedb import ArcadeDBError +from arcadedb import ArcadeDBError, ConflictError, DuplicateKeyError, PartialCommitError @pytest.fixture @@ -32,11 +35,21 @@ def db(temp_db_path): database.drop() +def _insert_rows(db): + with db.transaction(): + for _ in range(25): + db.command("sql", "INSERT INTO R SET k = 0, v = 0") + + def _count(db, where="true"): sql = f"SELECT count(*) AS c FROM R WHERE {where}" # nosec B608 - test-owned predicate text, no user input return db.query("sql", sql).first().get("c") +def _counter(db): + return db.query("sql", "SELECT n FROM C").first().get("n") + + def _commit_from_another_thread(db): """Commit a write to the record the block also wrote, so the block's own commit meets a ConcurrentModificationException.""" errors = [] @@ -66,32 +79,59 @@ def _batch_boundary(db): db.command("sql", "UPDATE R SET v = v + 1 BATCH 10") -@pytest.mark.parametrize( - "publish, durable_v1", - [ - pytest.param(_batch_boundary, 20, id="batch-boundary"), - pytest.param(_commit_inside_the_block, 25, id="commit-inside-the-block"), - ], -) -def test_a_block_that_committed_part_of_its_work_is_not_replayed( - db, publish, durable_v1 -): - with db.transaction(): - for _ in range(25): - db.command("sql", "INSERT INTO R SET k = 0, v = 0") - attempts = [] +PUBLISH = [ + pytest.param(_batch_boundary, 20, id="batch-boundary"), + pytest.param(_commit_inside_the_block, 25, id="commit-inside-the-block"), +] + + +def _losing_block(db, publish, attempts): + """A block that commits part of its work (``publish``), then loses a conflict at its commit on the first attempt.""" def fn(): attempts.append(1) - publish(db) + if publish is not None: + publish(db) db.command("sql", "UPDATE C SET n = n + 1") if len(attempts) == 1: _commit_from_another_thread(db) return "done" - with pytest.raises(ArcadeDBError, match="ConcurrentModification"): - db.run_in_transaction(fn, retries=5, backoff_s=0) + return fn + +def _assert_refusal(error, block): + assert type(error) is PartialCommitError + assert not isinstance(error, ConflictError) + assert error.code == "partial_commit" + assert "Part of the work is already committed" in error.hint + assert "check what was applied" in error.hint + text = str(error) + assert "run the whole transaction again" not in text + assert ( + f"{block} committed part of its work before failing with ConcurrentModificationException" + in text + ) + # the conflict stays visible, but nothing that follows the cause chain to decide on a retry finds it + assert error.__cause__ is None + assert isinstance(error.__context__, ArcadeDBError) + assert error.__context__.code == "conflict" + + +@pytest.mark.parametrize("retries", [5, 0], ids=["retries-left", "last-attempt"]) +@pytest.mark.parametrize("publish, durable_v1", PUBLISH) +def test_a_block_that_committed_part_of_its_work_is_not_replayed( + db, publish, durable_v1, retries +): + _insert_rows(db) + attempts = [] + + with pytest.raises(PartialCommitError) as raised: + db.run_in_transaction( + _losing_block(db, publish, attempts), retries=retries, backoff_s=0 + ) + + _assert_refusal(raised.value, "run_in_transaction block") assert ( len(attempts) == 1 ), "the block was replayed after it had committed part of its work" @@ -101,6 +141,59 @@ def fn(): assert not db.is_transaction_active() +@pytest.mark.parametrize("publish, durable_v1", PUBLISH) +def test_a_caller_that_follows_the_hint_applies_nothing_twice(db, publish, durable_v1): + """A conflict's hint says to run the whole transaction again, and a program retries on ``ConflictError`` (#504).""" + _insert_rows(db) + attempts = [] + fn = _losing_block(db, publish, attempts) + + try: + db.run_in_transaction(fn, retries=5, backoff_s=0) + except ConflictError: + db.run_in_transaction(fn, retries=5, backoff_s=0) + except PartialCommitError: + pass + + assert _count(db, "v = 2") == 0, "the committed part was applied a second time" + assert _count(db, "v = 1") == durable_v1 + + +@pytest.mark.parametrize("raised_by", ["end-of-the-block", "commit-inside-the-block"]) +@pytest.mark.parametrize("publish, durable_v1", PUBLISH) +def test_a_with_block_that_committed_part_of_its_work_raises_the_same_error( + db, publish, durable_v1, raised_by +): + _insert_rows(db) + + with pytest.raises(PartialCommitError) as raised: + with db.transaction(): + publish(db) + db.command("sql", "UPDATE C SET n = n + 1") + _commit_from_another_thread(db) + if raised_by == "commit-inside-the-block": + db.commit() + + _assert_refusal(raised.value, "Transaction block") + assert _count(db, "v = 1") == durable_v1 + assert _counter(db) == 100 + assert not db.is_transaction_active() + + +def test_a_with_block_that_committed_nothing_still_raises_a_conflict(db): + _insert_rows(db) # the thread's transaction context has commits behind it + + with pytest.raises(ConflictError) as raised: + with db.transaction(): + db.command("sql", "INSERT INTO R SET k = 1, v = 0") + db.command("sql", "UPDATE C SET n = n + 1") + _commit_from_another_thread(db) + + assert raised.value.code == "conflict" + assert _count(db, "k = 1") == 0 + assert not db.is_transaction_active() + + def test_a_block_that_committed_nothing_is_still_retried(db): """The guard must not turn every conflict into a refusal: a block with no durable part is replayed, once, and succeeds.""" attempts = [] @@ -117,4 +210,206 @@ def fn(): assert len(attempts) == 2 assert _count(db, "k = 1") == 1 # the first attempt was rolled back; the other thread added 100 and the second attempt 1 - assert db.query("sql", "SELECT n FROM C").first().get("n") == 101 + assert _counter(db) == 101 + + +def test_a_nested_block_that_committed_nothing_is_still_retried(db): + """Inside a caller's transaction the block has a transaction of its own, whose commits are what counts.""" + _insert_rows(db) # the caller's context has commits behind it, the block's has none + attempts = [] + + with db.transaction(): + assert ( + db.run_in_transaction( + _losing_block(db, None, attempts), retries=5, backoff_s=0 + ) + == "done" + ) + + assert len(attempts) == 2 + assert _counter(db) == 101 + + +def test_a_nested_with_block_that_committed_nothing_still_raises_a_conflict(db): + _insert_rows(db) + + with db.transaction(): + with pytest.raises(ConflictError): + with db.transaction(): + db.command("sql", "UPDATE C SET n = n + 1") + _commit_from_another_thread(db) + + assert _counter(db) == 100 + + +@pytest.mark.parametrize("first_use", [False, True], ids=["used-thread", "new-thread"]) +@pytest.mark.parametrize("publish, durable_v1", PUBLISH) +def test_a_nested_block_that_committed_part_of_its_work_is_not_replayed( + db, publish, durable_v1, first_use +): + """On a new thread the caller's context has committed nothing, on a used one it has: neither says what the block did.""" + _insert_rows(db) + attempts = [] + outcome = [] + + def caller(): + try: + with db.transaction(): + db.run_in_transaction( + _losing_block(db, publish, attempts), retries=5, backoff_s=0 + ) + except BaseException as e: # checked on the test's thread + outcome.append(e) + + if first_use: + thread = threading.Thread(target=caller) + thread.start() + thread.join() + else: + caller() + + assert len(attempts) == 1 + assert len(outcome) == 1 + _assert_refusal(outcome[0], "run_in_transaction block") + assert _count(db, "v = 2") == 0 + assert _count(db, "v = 1") == durable_v1 + + +@pytest.mark.parametrize("publish, durable_v1", PUBLISH) +def test_a_nested_with_block_that_committed_part_of_its_work_raises_the_same_error( + db, publish, durable_v1 +): + _insert_rows(db) + + with db.transaction(): + with pytest.raises(PartialCommitError) as raised: + with db.transaction(): + publish(db) + db.command("sql", "UPDATE C SET n = n + 1") + _commit_from_another_thread(db) + + _assert_refusal(raised.value, "Transaction block") + assert _count(db, "v = 1") == durable_v1 + + +@pytest.mark.parametrize("publish, durable_v1", PUBLISH) +def test_an_outer_run_in_transaction_does_not_replay_the_refusal( + db, publish, durable_v1 +): + _insert_rows(db) + outer_attempts = [] + inner_attempts = [] + + def outer(): + outer_attempts.append(1) + db.run_in_transaction( + _losing_block(db, publish, inner_attempts), retries=5, backoff_s=0 + ) + + with pytest.raises(PartialCommitError): + db.run_in_transaction(outer, retries=5, backoff_s=0) + + assert (len(outer_attempts), len(inner_attempts)) == (1, 1) + assert _count(db, "v = 1") == durable_v1 + assert not db.is_transaction_active() + + +def test_a_conflict_that_the_block_wraps_is_refused_too(db): + """An exception of the program's own, raised from the conflict, is what ``run_in_transaction`` would retry on the JVM build.""" + _insert_rows(db) + attempts = [] + + def fn(): + attempts.append(1) + _commit_inside_the_block(db) + db.command("sql", "UPDATE C SET n = n + 1") + _commit_from_another_thread(db) + try: + db.commit() + except ConflictError as e: + raise RuntimeError("could not store the step") from e + + with pytest.raises(PartialCommitError) as raised: + db.run_in_transaction(fn, retries=5, backoff_s=0) + + assert len(attempts) == 1 + assert isinstance(raised.value.__context__, RuntimeError) + assert raised.value.__cause__ is None + + +def test_a_duplicated_key_after_a_commit_is_raised_as_it_is(db): + """Nobody is told to retry a duplicated key, so it keeps its class, as in the engine; the block is not run again either.""" + db.command("sql", "CREATE DOCUMENT TYPE U") + db.command("sql", "CREATE PROPERTY U.k INTEGER") + db.command("sql", "CREATE INDEX ON U (k) UNIQUE") + attempts = [] + + def fn(): + attempts.append(1) + db.command("sql", "INSERT INTO U SET k = 1") + db.commit() + db.begin() + db.command("sql", "INSERT INTO U SET k = 1") + + with pytest.raises(DuplicateKeyError): + db.run_in_transaction(fn, retries=5, backoff_s=0) + + assert len(attempts) == 1 + + +def _engine_raises_its_own_refusal(db): + """Whether the engine's retry loops answer such a block with a ``TransactionException`` of their own (engine PR 13406). + + None when it cannot be told from here: the native build on a 26.12.1 snapshot, which may be older or newer than the change. + """ + if arcadedb.__backend__ != "native": + import jpype + + context = jpype.JClass("com.arcadedb.database.TransactionContext") + return hasattr(context, "notReplayable") + version = str(db.query("sql", "SELECT version() AS v").first().get("v")).split()[0] + if version.startswith("26.11."): + return False + return None if "SNAPSHOT" in version else True + + +def test_the_engines_own_refusal_gets_the_same_class_and_code(db): + """``COMMIT RETRY`` is a retry loop of the engine. From engine 26.12.1 it refuses a block that committed part of its work with + a ``TransactionException`` of its own; an older engine raises the conflict. + """ + _insert_rows(db) + calls = [] + + def conflict_once(): + calls.append(1) + if len(calls) == 1: + _commit_from_another_thread(db) + return len(calls) + + db.register_function("conflict_once", conflict_once) + script = ( + "BEGIN;" + "UPDATE R SET v = v + 1 BATCH 10;" + "UPDATE C SET n = n + 1;" + "LET called = SELECT conflict_once() AS c;" + "COMMIT RETRY 5;" + ) + try: + with pytest.raises(ArcadeDBError) as raised: + db.command("sqlscript", script).to_list() + finally: + db.unregister_function("conflict_once") + + error = raised.value + assert calls == [1], "the engine replayed the block" + assert _count(db, "v = 1") == 20 + refused = "committed part of its work" in str(error) + expected = _engine_raises_its_own_refusal(db) + if expected is not None: + assert refused is expected, str(error) + if refused: + assert type(error) is PartialCommitError, str(error) + assert error.code == "partial_commit" + assert error.cause == "com.arcadedb.exception.TransactionException" + else: + assert type(error) is ConflictError, str(error) diff --git a/tests/test_run_in_transaction_retry.py b/tests/test_run_in_transaction_retry.py index 59523351..966efc5d 100644 --- a/tests/test_run_in_transaction_retry.py +++ b/tests/test_run_in_transaction_retry.py @@ -21,6 +21,7 @@ import arcadedb from arcadedb import ArcadeDBError +from arcadedb.exceptions import _retry_verdict def _java(name): @@ -206,9 +207,13 @@ def fn(): ) ) - with pytest.raises(ArcadeDBError, match="ConcurrentModificationException"): + with pytest.raises( + arcadedb.PartialCommitError, match="ConcurrentModificationException" + ) as raised: db.run_in_transaction(fn, retries=5, backoff_s=0) assert len(attempts) == 1 + # no retry loop finds the conflict behind the refusal: it is not in the cause chain + assert _retry_verdict(raised.value) == (None, 0) assert ( db.query("sql", "SELECT count(*) AS c FROM R WHERE v = 2").first().get("c") == 0 ) diff --git a/tests/test_transaction_context_interrupt.py b/tests/test_transaction_context_interrupt.py index 9c796876..285314e4 100644 --- a/tests/test_transaction_context_interrupt.py +++ b/tests/test_transaction_context_interrupt.py @@ -39,8 +39,14 @@ def rollback(self): def commit(self): self.active = False - def _transaction_stack_mark(self): - return self.active, self.depth + def _transaction_marks(self): + return (self.active, self.depth), 0 + + def _commit_witness(self, mark, commits): + return None + + def _partial_commit_refusal(self, failure, witness, block): + return None def _end_transactions_opened_since(self, mark): was_active, depth_before = mark