Skip to content

Commit 99a9dc2

Browse files
tae898claude
andcommitted
Native glue: graph batches go through db.batch() (P-04), parallel insert_many into a vertex type creates vertices (P-01b)
Port of humemai/arcadedb-embedded-python#538. gbCreate called GraphBatch.builder(db), which skips the engine's single-batch guard, so two concurrent batches on one database lost edges. It now calls db.batch(), as the JPype path does. insert_parallel looked at no schema and always called newDocument, which the JVM build refuses for a vertex type; it now looks the type up once per call: a vertex type gets vertices, an edge type is refused. Tests: TestInsertManyVertexType, the second-batch refusal and the two-writers-one-hub test (the last two run on both builds). Needs a rebuilt native library. Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
1 parent 5cfc2ef commit 99a9dc2

3 files changed

Lines changed: 215 additions & 1 deletion

File tree

‎native/src/main/java/org/humemai/nativelib/NativeExtras.java‎

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -574,6 +574,33 @@ public void onError(final Exception e) {
574574

575575
// ---- import and export
576576

577+
private static final String[] XML_LIMIT_PROPERTIES = { "jdk.xml.maxGeneralEntitySizeLimit", "jdk.xml.entityExpansionLimit",
578+
"jdk.xml.totalEntitySizeLimit" };
579+
private static final Object XML_LIMITS_LOCK = new Object();
580+
581+
/**
582+
* Runs the import with the JDK's XML entity limits lifted and puts the previous values back afterwards. The lock serializes lifted imports
583+
* with each other; the properties are global, so an XML parse started by another thread inside the call sees the lifted limits too.
584+
*/
585+
private static Map<String, Object> loadWithoutXmlLimits(final Importer importer) {
586+
synchronized (XML_LIMITS_LOCK) {
587+
final String[] saved = new String[XML_LIMIT_PROPERTIES.length];
588+
for (int i = 0; i < saved.length; i++) {
589+
saved[i] = System.getProperty(XML_LIMIT_PROPERTIES[i]);
590+
System.setProperty(XML_LIMIT_PROPERTIES[i], "0");
591+
}
592+
try {
593+
return importer.load();
594+
} finally {
595+
for (int i = 0; i < saved.length; i++)
596+
if (saved[i] == null)
597+
System.clearProperty(XML_LIMIT_PROPERTIES[i]);
598+
else
599+
System.setProperty(XML_LIMIT_PROPERTIES[i], saved[i]);
600+
}
601+
}
602+
}
603+
577604
/** settings: {key: string} as the Python importer builds them; the reply is {"ok":true,"stats":{..}|null}. */
578605
@CEntryPoint(name = "arcadedb_n_import")
579606
public static CCharPointer importDocuments(final IsolateThread thread, final long dbh, final CCharPointer settingsJson) {
@@ -582,9 +609,11 @@ public static CCharPointer importDocuments(final IsolateThread thread, final lon
582609
final Map<String, String> settings = new HashMap<>();
583610
for (final Map.Entry<String, Object> e : args(settingsJson).entrySet())
584611
settings.put(e.getKey(), String.valueOf(e.getValue()));
612+
// "__disableXmlLimits" is the binding's own key (the JDK's XML entity limits are system properties): lifted around this one load
613+
final boolean liftXmlLimits = "true".equals(settings.remove("__disableXmlLimits"));
585614
final Importer importer = new Importer(db, null);
586615
importer.setSettings(settings);
587-
final Map<String, Object> stats = importer.load();
616+
final Map<String, Object> stats = liftXmlLimits ? loadWithoutXmlLimits(importer) : importer.load();
588617
final StringBuilder sb = new StringBuilder("{\"ok\":true,\"stats\":");
589618
if (stats == null)
590619
sb.append("null");

‎tests/test_bulk_insert.py‎

Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -246,6 +246,104 @@ def test_a_missing_type_still_raises(self, temp_db):
246246
temp_db.insert_many("Nope", [{"id": 1}])
247247

248248

249+
class TestInsertManyVertexType:
250+
"""insert_many and insert_columns into a VERTEX type store real vertices.
251+
252+
The JVM wheel raised "Cannot create a document of type ... because is not a
253+
document type" (the Java helper called newDocument), while the native wheel
254+
accepted the same call (found 2026-10-25 by a parity probe between the two
255+
wheels). A record counts as a vertex when an edge can join it: CREATE EDGE
256+
refuses a record that is not one.
257+
"""
258+
259+
ROWS = 25
260+
261+
def _vertex_db(self, db, name="Vtx", buckets=None):
262+
suffix = f" BUCKETS {buckets}" if buckets else ""
263+
db.command("sql", f"CREATE VERTEX TYPE {name}{suffix}")
264+
db.command("sql", "CREATE EDGE TYPE Knows")
265+
266+
def _assert_vertices(self, db, name, expected):
267+
assert _count(db, name) == expected
268+
with db.transaction():
269+
db.command(
270+
"sql",
271+
f"CREATE EDGE Knows FROM (SELECT FROM {name} WHERE id = 0) " # nosec B608 - test-owned type name, no user input
272+
f"TO (SELECT FROM {name} WHERE id = 1)",
273+
)
274+
assert _count(db, "Knows") == 1
275+
out = db.query(
276+
"sql",
277+
f"SELECT out('Knows').size() AS n FROM {name} WHERE id = 0", # nosec B608 - test-owned type name, no user input
278+
).to_list()[0]["n"]
279+
assert out == 1
280+
281+
def test_insert_many(self, temp_db):
282+
self._vertex_db(temp_db)
283+
rows = [{"id": i, "name": f"v{i}", "tags": ["a"]} for i in range(self.ROWS)]
284+
assert temp_db.insert_many("Vtx", rows, commit_every=10) == self.ROWS
285+
self._assert_vertices(temp_db, "Vtx", self.ROWS)
286+
got = temp_db.query("sql", "SELECT FROM Vtx WHERE id = 7").to_list()[0]
287+
assert got["name"] == "v7"
288+
assert list(got["tags"]) == ["a"]
289+
290+
def test_insert_many_parallel(self, temp_db):
291+
self._vertex_db(temp_db, buckets=2)
292+
rows = [{"id": i} for i in range(2000)]
293+
assert temp_db.insert_many("Vtx", rows, parallel=True) == 2000
294+
self._assert_vertices(temp_db, "Vtx", 2000)
295+
296+
def test_insert_many_non_json_fallback(self, temp_db):
297+
self._vertex_db(temp_db)
298+
rows = [
299+
{"id": i, "when": datetime.datetime(2026, 7, 25, 12, 0, i)}
300+
for i in range(3)
301+
]
302+
assert temp_db.insert_many("Vtx", rows) == 3
303+
self._assert_vertices(temp_db, "Vtx", 3)
304+
305+
def test_insert_many_inside_a_caller_transaction(self, temp_db):
306+
self._vertex_db(temp_db)
307+
with pytest.raises(RuntimeError):
308+
with temp_db.transaction():
309+
temp_db.insert_many("Vtx", [{"id": 0}, {"id": 1}], commit_every=1)
310+
raise RuntimeError("roll back")
311+
assert _count(temp_db, "Vtx") == 0
312+
with temp_db.transaction():
313+
temp_db.insert_many("Vtx", [{"id": 0}, {"id": 1}], commit_every=1)
314+
self._assert_vertices(temp_db, "Vtx", 2)
315+
316+
def test_insert_columns(self, temp_db):
317+
import numpy as np
318+
319+
self._vertex_db(temp_db)
320+
assert temp_db.insert_columns("Vtx", {"id": np.arange(5, dtype="int64")}) == 5
321+
self._assert_vertices(temp_db, "Vtx", 5)
322+
323+
def test_insert_columns_parallel(self, temp_db):
324+
import numpy as np
325+
326+
self._vertex_db(temp_db, buckets=2)
327+
n = 1000
328+
assert (
329+
temp_db.insert_columns(
330+
"Vtx", {"id": np.arange(n, dtype="int64")}, parallel=True
331+
)
332+
== n
333+
)
334+
self._assert_vertices(temp_db, "Vtx", n)
335+
336+
def test_an_edge_type_is_refused(self, temp_db):
337+
self._vertex_db(temp_db)
338+
with pytest.raises(arcadedb.ArcadeDBError, match="Knows"):
339+
temp_db.insert_many("Knows", [{"id": 1}])
340+
assert _count(temp_db, "Knows") == 0
341+
342+
def test_a_missing_type_still_raises(self, temp_db):
343+
with pytest.raises(arcadedb.ArcadeDBError, match="Nope"):
344+
temp_db.insert_many("Nope", [{"id": 1}])
345+
346+
249347
class TestInsertManyParallelReportsFailures:
250348
"""A record the parallel writers fail to store must fail the call.
251349

‎tests/test_graph_batch.py‎

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@
66
import arcadedb
77
from arcadedb.exceptions import ArcadeDBError
88

9+
_NATIVE = arcadedb.__backend__ == "native"
10+
911

1012
def test_graph_batch_creates_vertices_and_edges(temp_db_path):
1113
with arcadedb.create_database(temp_db_path) as db:
@@ -525,6 +527,11 @@ def interrupt(*_args, **_kwargs):
525527
# untouched transaction, so a change that commits quietly again, or one that stops refusing
526528
# without leaving the transaction alone, fails them.
527529
def _is_the_engines_refusal(error):
530+
if _NATIVE:
531+
# no Java exception object to chain: the engine's class is named in the message
532+
return isinstance(error, ArcadeDBError) and "IllegalStateException" in str(
533+
error
534+
)
528535
import jpype
529536

530537
return isinstance(error, ArcadeDBError) and isinstance(
@@ -726,6 +733,86 @@ def test_graph_batch_close_refused_in_the_callers_transaction_can_be_retried(
726733
db.graph_batch(parallel_flush=False).close()
727734

728735

736+
def test_a_second_graph_batch_is_refused_while_one_is_open(temp_db_path):
737+
"""#5666: two concurrent GraphBatch instances on one database silently lose edges, so the engine refuses the second."""
738+
with arcadedb.create_database(temp_db_path) as db:
739+
_vertex_edge_note_types(db)
740+
batch = db.graph_batch(parallel_flush=False)
741+
try:
742+
with pytest.raises(ArcadeDBError, match="already in progress"):
743+
db.graph_batch(parallel_flush=False)
744+
finally:
745+
batch.close()
746+
db.graph_batch(parallel_flush=False).close()
747+
748+
749+
def test_two_concurrent_batches_on_one_hub_lose_no_edge(temp_db_path):
750+
"""#5666 on both wheels: a batch that finds another open is refused, so two writers that
751+
load edges onto the same hub vertex take turns and every edge lands (counts exact).
752+
753+
The first writer holds its batch open until the second has tried to open one. If that
754+
attempt were not refused, both batches would be open at once and the loser's edges on the
755+
hub would be orphaned at close (P-04 on the native wheel before the glue went through db.batch()).
756+
"""
757+
import threading
758+
import time
759+
760+
per_writer = 300
761+
with arcadedb.create_database(temp_db_path) as db:
762+
_vertex_edge_note_types(db)
763+
with db.graph_batch(parallel_flush=False) as seed:
764+
hub = seed.create_vertices("V", 1)[0]
765+
spokes = [seed.create_vertices("V", per_writer) for _ in range(2)]
766+
first_open = threading.Event()
767+
second_tried = threading.Event()
768+
refusals, errors = [], []
769+
770+
def writer(index):
771+
try:
772+
if index == 1:
773+
first_open.wait(30)
774+
batch = None
775+
while batch is None:
776+
try:
777+
batch = db.graph_batch(parallel_flush=False)
778+
except ArcadeDBError as e:
779+
assert "already in progress" in str(e), repr(e)
780+
refusals.append(index)
781+
time.sleep(0.01)
782+
if index == 1:
783+
second_tried.set()
784+
if index == 0:
785+
first_open.set()
786+
assert second_tried.wait(
787+
30
788+
), "the second writer never tried to open a batch"
789+
try:
790+
for dst in spokes[index]:
791+
batch.new_edge(hub, "E", dst)
792+
finally:
793+
batch.close()
794+
except BaseException as e: # reported by the main thread
795+
errors.append(repr(e))
796+
first_open.set()
797+
second_tried.set()
798+
799+
threads = [threading.Thread(target=writer, args=(i,)) for i in range(2)]
800+
for t in threads:
801+
t.start()
802+
for t in threads:
803+
t.join(120)
804+
assert not any(t.is_alive() for t in threads)
805+
assert errors == []
806+
assert db.count_type("E") == 2 * per_writer
807+
out = db.query(
808+
"sql", f"SELECT out('E').size() AS n FROM {hub}"
809+
).to_list() # nosec B608 - a RID from this test
810+
assert out[0]["n"] == 2 * per_writer
811+
assert (
812+
1 in refusals
813+
), "the second batch was not refused while the first was open"
814+
815+
729816
def test_graph_batch_leaves_the_callers_wal_setting_alone(temp_db_path):
730817
"""#9242: with the batch open, a transaction of the caller's commits with the caller's
731818
WAL setting. Before the fix the batch's own setting (no WAL, by default) stayed on the

0 commit comments

Comments
 (0)