From c1114d4d199fe31eb05b49582d96682c81845389 Mon Sep 17 00:00:00 2001 From: Taewoon Kim Date: Fri, 27 Nov 2026 20:09:00 +0900 Subject: [PATCH] Native get_stats returns only counters, and three tests fit engine 26.12.1 The weekly snapshot run failed four tests on 26.12.1-SNAPSHOT. get_stats (native): engine 26.12.1 adds a `metadata` map to the `schema:index:` row (https://redirect.github.com/ArcadeData/arcadedb/pull/13097). The native wheel returned every column outside a fixed list, so the map showed up as a counter. It now keeps integer columns outside that list, which matches the map of longs that the JVM wheel returns, and a later descriptive column of another type is left out too. Facets: the test called `rs.facets()`, but `facets` is a property. The branch only runs on an engine with FACETS, so it never ran on 26.11.1. Async callback ids: from 26.12.1 a transaction that read a page it had written is refused when another transaction committed to that page (https://redirect.github.com/ArcadeData/arcadedb/pull/11671). With several workers the test's scan_type shares a worker batch with a create_record, which is not run again, so the callbacks got ConflictError. The test is about callback ids, so it uses one worker. A new test pins the engine rule on both engines, and the async executor page says what a caller sees. --- .../ROOT/pages/how-to/async-executor.adoc | 2 + src/arcadedb/_native/schema_objects.py | 17 +++++-- tests/test_concurrency.py | 50 +++++++++++++++++++ tests/test_native_async_callbacks.py | 5 +- tests/test_native_count.py | 4 +- tests/test_vector_index_introspection.py | 37 ++++++++++++-- 6 files changed, 105 insertions(+), 10 deletions(-) diff --git a/docs/modules/ROOT/pages/how-to/async-executor.adoc b/docs/modules/ROOT/pages/how-to/async-executor.adoc index ba4f17e9..4768e171 100644 --- a/docs/modules/ROOT/pages/how-to/async-executor.adoc +++ b/docs/modules/ROOT/pages/how-to/async-executor.adoc @@ -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") diff --git a/src/arcadedb/_native/schema_objects.py b/src/arcadedb/_native/schema_objects.py index 179a2375..7227b77e 100644 --- a/src/arcadedb/_native/schema_objects.py +++ b/src/arcadedb/_native/schema_objects.py @@ -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:`` row (the row's own columns left out).""" + """The engine's live counters of the primary bucket index, from its ``schema:index:`` row (:func:`_index_counters`).""" bucket = self._live_info()["bucket"] rows = self._database.query( "sql", @@ -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.""" @@ -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:`` 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", diff --git a/tests/test_concurrency.py b/tests/test_concurrency.py index 59c0739b..5796919c 100644 --- a/tests/test_concurrency.py +++ b/tests/test_concurrency.py @@ -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 @@ -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) diff --git a/tests/test_native_async_callbacks.py b/tests/test_native_async_callbacks.py index 4919ef38..1229099a 100644 --- a/tests/test_native_async_callbacks.py +++ b/tests/test_native_async_callbacks.py @@ -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) diff --git a/tests/test_native_count.py b/tests/test_native_count.py index 0a7491ea..15de032c 100644 --- a/tests/test_native_count.py +++ b/tests/test_native_count.py @@ -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 @@ -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): diff --git a/tests/test_vector_index_introspection.py b/tests/test_vector_index_introspection.py index ce8e6787..6f0c30a1 100644 --- a/tests/test_vector_index_introspection.py +++ b/tests/test_vector_index_introspection.py @@ -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:`` 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)