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: 2 additions & 0 deletions docs/modules/ROOT/pages/how-to/async-executor.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ The blocks on this page run one after the other against one empty database, and

Each worker of the executor opens a transaction of its own and commits it after `commit_every` operations, and at `wait_completion()`. You open no transaction for it. At parallel level 1 there is one worker, and every statement of the next block is stored once `wait_completion()` returns.

With two or more workers, two of these transactions can write to the same page, and the one that commits second can lose. The engine merges inserts that do not collide. It runs the `command` calls of a losing transaction again, up to `arcadedb.txRetries` times, but not when that transaction also holds a record or edge write such as `create_record` or `new_edge`. A transaction that cannot commit is rolled back, and the failure, a `ConflictError`, goes to the `on_error` handler and to the error callbacks of its commands and records. From engine 26.12.1, reads count too (ArcadeData/arcadedb#11671): if a `query` or `scan_type` reads a page that the transaction of its worker wrote, and another worker commits to that page first, the transaction is refused. So at parallel level 2 or higher, give every write an `error_callback`, and use parallel level 1 where every call must succeed and no other thread writes the same types.

[source,python]
----
db.command("sql", "CREATE DOCUMENT TYPE Item")
Expand Down
17 changes: 14 additions & 3 deletions src/arcadedb/_native/schema_objects.py
Original file line number Diff line number Diff line change
Expand Up @@ -547,7 +547,7 @@ def get_size(self):
return super().get_size()

def get_stats(self):
"""The engine's live counters of the primary bucket index, from its ``schema:index:<name>`` row (the row's own columns left out)."""
"""The engine's live counters of the primary bucket index, from its ``schema:index:<name>`` row (:func:`_index_counters`)."""
bucket = self._live_info()["bucket"]
rows = self._database.query(
"sql",
Expand All @@ -557,7 +557,7 @@ def get_stats(self):
raise ArcadeDBError(
f"Failed to read vector index stats: no index {bucket!r}"
)
return {k: v for k, v in rows[0].items() if k not in _INDEX_ROW_COLUMNS}
return _index_counters(rows[0])

def get_metadata(self):
"""The engine's configuration of the index: what this session created and what an index opened from disk carries, defaults included."""
Expand All @@ -576,7 +576,18 @@ def get_quantization(self):
return str(self._live_info()["quantization"] or "NONE")


# the descriptive columns of a schema:index row; every other column is a counter of IndexInternal.getStats()
def _index_counters(row):
"""The counters of a ``schema:index:<name>`` row, as the JVM build returns them from ``IndexInternal.getStats()``.

That is a map of longs, so a counter is an integer column that does not describe the index. A column of any other type is
the engine describing the index, also one a later engine adds (26.12.1 added the ``metadata`` map).
"""
return {
k: v for k, v in row.items() if type(v) is int and k not in _INDEX_ROW_COLUMNS
}


# the descriptive columns of a schema:index row (an integer one among them would pass for a counter)
_INDEX_ROW_COLUMNS = frozenset(
{
"name",
Expand Down
50 changes: 50 additions & 0 deletions tests/test_concurrency.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import subprocess # nosec B404
import sys
import textwrap
import threading
import time
from concurrent.futures import ThreadPoolExecutor
from statistics import mean
Expand Down Expand Up @@ -180,6 +181,55 @@ def test_sequential_access(cleanup_db):
db3.close()


def _engine_version(db):
"""The engine's x.y.z through SQL ``SELECT version()``; a SNAPSHOT or a build suffix is dropped."""
raw = str(db.query("sql", "SELECT version() AS v").first().get("v"))
parts = [
int(p) if p.isdigit() else 0
for p in raw.split()[0].split("-")[0].split(".")[:3]
]
return tuple(parts + [0] * (3 - len(parts)))


@pytest.mark.parametrize("reads_the_page", [False, True])
def test_a_commit_that_read_a_page_another_transaction_changed(temp_db, reads_the_page):
"""Two transactions insert into the same page, and the one that commits second is merged, unless it also read that page.

From engine 26.12.1 (ArcadeData/arcadedb#11671) a transaction that has written a page reads its own copy of it, so a scan
after another commit to the page decided on stale rows, and its commit is refused with ``ConflictError``. Older engines
merge it. Blind inserts merge on both.
"""
temp_db.command("sql", "CREATE DOCUMENT TYPE Item")
with temp_db.transaction():
temp_db.command("sql", "INSERT INTO Item SET n = 0")
other_errors = []

def insert_in_another_transaction():
try:
with temp_db.transaction():
temp_db.command("sql", "INSERT INTO Item SET n = 2")
except Exception as exc: # pragma: no cover - reported by the assert below
other_errors.append(exc)

refused = reads_the_page and _engine_version(temp_db) >= (26, 12, 1)
temp_db.begin()
temp_db.command("sql", "INSERT INTO Item SET n = 1")
other = threading.Thread(target=insert_in_another_transaction)
other.start()
other.join()
assert other_errors == []
if reads_the_page:
temp_db.query("sql", "SELECT FROM Item").to_list()
if refused:
with pytest.raises(arcadedb.ConflictError):
temp_db.commit()
else:
temp_db.commit()

stored = sorted(r.get("n") for r in temp_db.query("sql", "SELECT n FROM Item"))
assert stored == ([0, 2] if refused else [0, 1, 2])


def test_concurrent_access_limitation(cleanup_db):
"""Test that concurrent access is properly prevented."""
print("\n" + "=" * 70)
Expand Down
5 changes: 4 additions & 1 deletion tests/test_native_async_callbacks.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,10 @@ def _submit_every_kind(db, executor, seen):

def test_wait_completion_gives_back_the_ids_of_every_kind_of_call(graph_db):
baseline = _size()
executor = graph_db.async_executor()
# One worker, because every call must succeed here. With more, several workers write the same page of Item and a batch can
# lose the race: engine 26.12.1 refuses one whose worker also read that page (ArcadeData/arcadedb#11671,
# test_concurrency.py), and a batch with a create_record is not run again.
executor = graph_db.async_executor().set_parallel_level(1)
seen = []
for _ in range(ROUNDS):
_submit_every_kind(graph_db, executor, seen)
Expand Down
4 changes: 2 additions & 2 deletions tests/test_native_count.py
Original file line number Diff line number Diff line change
Expand Up @@ -294,7 +294,7 @@ def _facets_after_to_list(db):
rs = db.query("sql", FACETS_Q)
rows = rs.to_list()
assert len(rows) == ROWS
facets = rs.facets()
facets = rs.facets
assert facets is not None
return facets

Expand All @@ -313,7 +313,7 @@ def test_count_then_facets_of_a_facets_query_returns_the_facets(db, foreign):
foreign.reset()
assert rs.count() == ROWS
assert "arcadedb_n_count" not in foreign.names # the statement was read row by row
assert rs.facets() == expected
assert rs.facets == expected


def test_a_statement_that_mentions_facets_is_counted_row_by_row(db, foreign):
Expand Down
37 changes: 33 additions & 4 deletions tests/test_vector_index_introspection.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,13 +82,42 @@ def test_values_are_plain_scalars_and_the_listing_columns_are_not_counters(
_insert(temp_db, UNIT_VECTORS)

stats = index.get_stats()
assert all(
v is None or isinstance(v, (int, float, bool, str)) for v in stats.values()
)
# the engine's counters are longs, so both wheels hand out plain ints
assert {k: v for k, v in stats.items() if type(v) is not int} == {}
# a schema:index row also names the index and describes it; get_stats is the counters only
for descriptive in ("name", "indexType", "typeName", "properties", "fileId"):
for descriptive in (
"name",
"indexType",
"typeName",
"properties",
"fileId",
"metadata",
):
assert descriptive not in stats

def test_the_native_filter_keeps_only_the_counters_of_an_index_row(self):
"""A ``schema:index:<name>`` row as engine 26.12.1 writes it: it has the ``metadata`` map beside the counters
(ArcadeData/arcadedb#13097). The row is written here, so the test says the same on every engine and needs no library.
"""
from arcadedb._native.schema_objects import _index_counters

counters = {"totalVectors": 3, "dimensions": 3, "asyncRebuildInProgress": 0}
described = {
"name": "Doc_0_1",
"indexType": "LSM_VECTOR",
"typeName": "Doc",
"properties": [["embedding"]],
"keyTypes": ["ARRAY_OF_FLOATS"],
"unique": False,
"automatic": True,
"fileId": 3,
"size": "64KB",
"associatedBucketId": 1,
"metadata": {"dimensions": 3, "addHierarchy": True},
"aColumnOfALaterEngine": ["x"],
}
assert _index_counters({**described, **counters}) == counters

def test_searches_move_the_search_counter(self, temp_db):
_make_type(temp_db)
index = temp_db.create_vector_index("Doc", "embedding", dimensions=3)
Expand Down
Loading