Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/modules/ROOT/pages/how-to/concurrency.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -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]
----
Expand Down
56 changes: 55 additions & 1 deletion docs/modules/ROOT/pages/how-to/errors.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -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`
Expand Down Expand Up @@ -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

Expand Down
2 changes: 2 additions & 0 deletions docs/modules/ROOT/pages/how-to/transactions.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
11 changes: 10 additions & 1 deletion docs/modules/ROOT/pages/upgrading.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -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].

Expand Down Expand Up @@ -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:
Expand Down
27 changes: 25 additions & 2 deletions native/src/main/java/org/humemai/nativelib/ArcadeNative.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -49,6 +50,13 @@ public final class ArcadeNative {
private static final Map<Long, ArcadeDBServer> 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<Map<Long, TransactionContext>> 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
Expand Down Expand Up @@ -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);
Expand All @@ -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 &lt;&lt; 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
Expand All @@ -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 -> {
}
}
Expand All @@ -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;
Expand Down
2 changes: 2 additions & 0 deletions src/arcadedb/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ def __getattr__(name: str) -> str:
DatabaseLockedError,
DatabaseNotFoundError,
DuplicateKeyError,
PartialCommitError,
QuerySyntaxError,
QueryTimeoutError,
RecordNotFoundError,
Expand Down Expand Up @@ -159,6 +160,7 @@ def __getattr__(name: str) -> str:
"DatabaseLockedError",
"DatabaseNotFoundError",
"DuplicateKeyError",
"PartialCommitError",
"QuerySyntaxError",
"QueryTimeoutError",
"RecordNotFoundError",
Expand Down
Loading
Loading