From e7aae64d4da0eb7bc17e325f836d1d7f082bee8e Mon Sep 17 00:00:00 2001 From: Taewoon Kim Date: Mon, 30 Nov 2026 07:48:33 +0900 Subject: [PATCH] graph_batch: refuse an edge endpoint that is not an existing vertex, before the call buffers anything GraphBatch.newEdge() takes its endpoints on trust. A RID of no record, or of a document, failed only at flush or close, after the edge records were written, and then no vertex led to the edges of the load. Both builds now check every endpoint before the first edge of a call is buffered: EdgeBatcher on the JVM build, NativeExtras (and a check_endpoints op) on the native one. The check is the one the engine's requireVertex makes; it is written here because the native build also links 26.11.1, which does not have that method. --- .../modules/ROOT/pages/how-to/bulk-loads.adoc | 6 + .../org/humemai/nativelib/NativeExtras.java | 38 +++++- src/arcadedb/_native/extras.py | 8 ++ src/arcadedb/graph_batch.py | 32 ++++- src/java/com/arcadedb/python/EdgeBatcher.java | 29 +++++ tests/test_graph_batch_bad_endpoints.py | 113 ++++++++++++++++++ 6 files changed, 218 insertions(+), 8 deletions(-) create mode 100644 tests/test_graph_batch_bad_endpoints.py diff --git a/docs/modules/ROOT/pages/how-to/bulk-loads.adoc b/docs/modules/ROOT/pages/how-to/bulk-loads.adoc index 99549224..aa1ff0f7 100644 --- a/docs/modules/ROOT/pages/how-to/bulk-loads.adoc +++ b/docs/modules/ROOT/pages/how-to/bulk-loads.adoc @@ -313,6 +313,12 @@ with db.graph_batch(batch_size=100, chunk_cache_capacity=1_000) as batch: Both arguments are bounds, not allocations you must reach: a batch that holds more edges than `batch_size` flushes early, and a cache that fills evicts entries and reloads them from the database on a miss. Leave them at their defaults for a bulk load of many edges in one batch. The numbers are one machine and single runs, so read them as an order of magnitude. +== Edge endpoints in a graph batch + +`GraphBatch.new_edge` and `GraphBatch.new_edges` take vertices or RIDs, on both packages, and check that every endpoint is a vertex that exists before they buffer an edge. A RID of no record raises `RecordNotFoundError`, a RID of a document or an edge raises `ArcadeDBError`, and both name the RID. A refused call buffers nothing, and the batch stays usable. The check reads each endpoint once for each edge, so it adds to the time of a large load. + +The check is there because the engine's batch takes the endpoints on trust: a flush or close that got a bad one failed after it had written the edge records, and then no vertex led to any edge of the load. A vertex that you delete between the call and the flush is not caught, so do not delete vertices while a batch that points at them is open. + == If a graph batch is interrupted This section is about a `graph_batch()` load that stops before `close()` returns, for example when the process is killed (`kill -9`, the out-of-memory killer, power loss). An exception inside a `with db.graph_batch() as batch:` block still runs `close()`. The numbers below come from a kill probe on the `arcadedb` (native) package: `kill -9` in the middle of the edge phase, the default `commit_every=1000`, with and without `use_wal=True`. In the 40 kills of the probe, no committed vertex or edge chunk was lost, no record was torn, no edge pointed at a missing vertex, and every database reopened and accepted writes. The example below is one of these kills: 30,000 vertices and 70,000 edge records were in the database afterwards. diff --git a/native/src/main/java/org/humemai/nativelib/NativeExtras.java b/native/src/main/java/org/humemai/nativelib/NativeExtras.java index cddd925b..bd716f10 100644 --- a/native/src/main/java/org/humemai/nativelib/NativeExtras.java +++ b/native/src/main/java/org/humemai/nativelib/NativeExtras.java @@ -36,6 +36,7 @@ import com.arcadedb.event.BeforeRecordDeleteListener; import com.arcadedb.event.BeforeRecordUpdateListener; import com.arcadedb.exception.DatabaseOperationException; +import com.arcadedb.exception.RecordNotFoundException; import com.arcadedb.function.CypherBuiltinFunctions; import com.arcadedb.function.CypherFunctionRegistry; import com.arcadedb.function.FunctionRegistry; @@ -220,6 +221,28 @@ static void newEdgesJoined(final GraphBatch batch, final String src, final Strin } } + /** + * Refuses an endpoint that is not an existing vertex, as EdgeBatcher does on the JPype path (ArcadeData/arcadedb-python#506): + * GraphBatch.newEdge() takes its endpoints on trust, and a flush or close that gets a bad one leaves the whole load unreachable. + */ + private static void requireVertex(final Database db, final RID rid) { + if (!db.existsRecord(rid)) + throw new RecordNotFoundException("Vertex " + rid + " does not exist", rid); + if (!(db.getSchema().getTypeByBucketId(rid.getBucketId()) instanceof VertexType)) + throw new IllegalArgumentException("Record " + rid + " is not a vertex"); + } + + /** requireVertex for every RID of a ';'-joined text. */ + private static void requireVertices(final Database db, final String joined) { + for (int from = 0; from < joined.length(); ) { + int to = joined.indexOf(';', from); + if (to < 0) + to = joined.length(); + requireVertex(db, rid(joined, from, to)); + from = to + 1; + } + } + /** The RID of "#bucket:position" in text[from, to) (the '#' is optional); anything else goes through RID(String), which refuses it. */ private static RID rid(final String text, final int from, final int to) { int p = from; @@ -552,7 +575,8 @@ public static CCharPointer gbCreate(final IsolateThread thread, final long dbh, /** * ops: create_vertex {type, props} -> rid; create_vertices {type, count} | {type, rows} -> rids; new_edge {src, type, dst, props}; - * new_edges {src:[..], type, dst:[..], props:[..]|null}; flush; close; stats. + * new_edges {src:[..], type, dst:[..], props:[..]|null}; check_endpoints {src, dst} (';'-joined RIDs, before the new_edges calls); flush; + * close; stats. */ @CEntryPoint(name = "arcadedb_n_gb") public static CCharPointer gb(final IsolateThread thread, final long h, final CCharPointer op, final CCharPointer argsJson) { @@ -638,8 +662,16 @@ else if (opName.equals("create_vertices")) } return ArcadeNative.out("{\"ok\":true,\"rids\":" + ridList(rids) + "}"); } - case "new_edge" -> batch.newEdge(new RID((String) a.get("src")), (String) a.get("type"), new RID((String) a.get("dst")), - varargs(a.get("props"))); + case "new_edge" -> { + final RID src = new RID((String) a.get("src")), dst = new RID((String) a.get("dst")); + requireVertex(entry.db(), src); + requireVertex(entry.db(), dst); + batch.newEdge(src, (String) a.get("type"), dst, varargs(a.get("props"))); + } + case "check_endpoints" -> { + requireVertices(entry.db(), (String) a.get("src")); + requireVertices(entry.db(), (String) a.get("dst")); + } case "new_edges" -> { if (a.get("src") instanceof String srcText && a.get("dst") instanceof String dstText) { newEdgesJoined(batch, srcText, (String) a.get("type"), dstText); diff --git a/src/arcadedb/_native/extras.py b/src/arcadedb/_native/extras.py index f6ae3ff6..08c10b0e 100644 --- a/src/arcadedb/_native/extras.py +++ b/src/arcadedb/_native/extras.py @@ -407,6 +407,14 @@ def new_edges(self, source_rids, edge_type: str, destination_rids, properties=No f"Failed to buffer batch edges '{edge_type}': property names must be str, got {key!r}" ) chunk = self._BULK_CHUNK + # all chunks before the first edge is buffered, so a call with an endpoint that is not a vertex leaves nothing behind + for start in range(0, len(source_rids), chunk): + self._op( + f"Failed to buffer batch edges '{edge_type}'", + "check_endpoints", + src=";".join(source_rids[start : start + chunk]), + dst=";".join(destination_rids[start : start + chunk]), + ) if properties is None: # no properties: the RIDs of a chunk go over as two ';'-joined texts (as EdgeBatcher.newEdgesJoined takes them on the # JPype path) and are read straight into RIDs, not as two JSON lists of Strings diff --git a/src/arcadedb/graph_batch.py b/src/arcadedb/graph_batch.py index 6ecfcb8d..2717b0c7 100644 --- a/src/arcadedb/graph_batch.py +++ b/src/arcadedb/graph_batch.py @@ -561,11 +561,24 @@ def new_edge( destination_vertex_or_rid: Any, **properties: Any, ) -> "GraphBatch": - """Buffer an edge for creation during flush or close.""" + """Buffer an edge for creation during flush or close. + + Both endpoints must be vertices that exist. A RID of no record raises + RecordNotFoundError and a RID of another kind of record raises + ArcadeDBError, each naming the RID, and the edge is not buffered. + """ self._check_not_closed() + from .results import _bridge_class + try: source_rid = self._to_java_rid(source_vertex_or_rid) destination_rid = self._to_java_rid(destination_vertex_or_rid) + edge_batcher = _bridge_class("EdgeBatcher") + if edge_batcher is not None and None not in (source_rid, destination_rid): + # a record that was never saved has no RID: newEdge() refuses it below + edge_batcher.requireEndpoints( + self._java_db, source_rid, destination_rid + ) if properties: self._java_graph_batch.newEdge( source_rid, @@ -602,6 +615,10 @@ def new_edges( edge lists). Each source and destination is a RID string ("#1:0"), a Java ``RID``, or a vertex or document, as for :meth:`new_edge`. + Every endpoint of the call is checked before its first edge is + buffered, as for :meth:`new_edge`: one that is not an existing vertex + raises, naming the RID, and no edge of the call is buffered. + Args: source_rids: Sequence of source vertex RIDs. edge_type: Edge type name. @@ -660,6 +677,15 @@ def new_edges( return self try: + sources = [self._rid_text(r) for r in source_rids] + dests = [self._rid_text(r) for r in destination_rids] + # all chunks before the first edge is buffered, so a refused call leaves nothing behind + for start in range(0, len(sources), self._BULK_CHUNK): + edge_batcher.requireEndpointsJoined( + self._java_db, + ";".join(sources[start : start + self._BULK_CHUNK]), + ";".join(dests[start : start + self._BULK_CHUNK]), + ) if properties is not None and not any(properties): # no edge has a property: the same call as no properties at all (a plain newEdge per edge) properties = None @@ -668,8 +694,6 @@ def new_edges( # copy; a Python list of N strings would be converted # element-by-element by JPype and eat the batching win. # Chunked so huge ingests never build one giant string. - sources = [self._rid_text(r) for r in source_rids] - dests = [self._rid_text(r) for r in destination_rids] for start in range(0, len(sources), self._BULK_CHUNK): edge_batcher.newEdgesJoined( self._java_graph_batch, @@ -686,8 +710,6 @@ def new_edges( ) if typed is not None: # properties of exact scalars: the RIDs cross as the joined texts above, the values as typed columns, one per property - sources = [self._rid_text(r) for r in source_rids] - dests = [self._rid_text(r) for r in destination_rids] step = self._BULK_CHUNK for k, (names, columns, nulls) in enumerate(typed): start = k * step diff --git a/src/java/com/arcadedb/python/EdgeBatcher.java b/src/java/com/arcadedb/python/EdgeBatcher.java index dd3ab529..8f6c9b09 100644 --- a/src/java/com/arcadedb/python/EdgeBatcher.java +++ b/src/java/com/arcadedb/python/EdgeBatcher.java @@ -11,14 +11,43 @@ */ package com.arcadedb.python; +import com.arcadedb.database.Database; import com.arcadedb.database.RID; +import com.arcadedb.exception.RecordNotFoundException; import com.arcadedb.graph.GraphBatch; +import com.arcadedb.schema.VertexType; public final class EdgeBatcher { private EdgeBatcher() { } + /** + * Refuses an endpoint that is not an existing vertex (ArcadeData/arcadedb-python#506). GraphBatch.newEdge() takes its endpoints on + * trust, and a flush or close that gets a bad one leaves every edge of the load unreachable. + */ + private static void requireVertex(final Database database, final RID rid) { + if (!database.existsRecord(rid)) + throw new RecordNotFoundException("Vertex " + rid + " does not exist", rid); + if (!(database.getSchema().getTypeByBucketId(rid.getBucketId()) instanceof VertexType)) + throw new IllegalArgumentException("Record " + rid + " is not a vertex"); + } + + /** The check for the two endpoints of one edge, before it is buffered. */ + public static void requireEndpoints(final Database database, final RID source, final RID destination) { + requireVertex(database, source); + requireVertex(database, destination); + } + + /** The check for the endpoints of a bulk call, as the joined texts of {@link #newEdgesJoined}, before any of its edges is buffered. */ + public static void requireEndpointsJoined(final Database database, final String joinedSourceRids, + final String joinedDestinationRids) { + for (final String rid : joinedSourceRids.split(";")) + requireVertex(database, new RID(rid)); + for (final String rid : joinedDestinationRids.split(";")) + requireVertex(database, new RID(rid)); + } + public static void newEdges(final GraphBatch batch, final String[] sourceRids, final String edgeType, final String[] destinationRids) { if (sourceRids.length != destinationRids.length) diff --git a/tests/test_graph_batch_bad_endpoints.py b/tests/test_graph_batch_bad_endpoints.py new file mode 100644 index 00000000..ac6250b7 --- /dev/null +++ b/tests/test_graph_batch_bad_endpoints.py @@ -0,0 +1,113 @@ +"""graph_batch refuses an edge endpoint that is not an existing vertex (ArcadeData/arcadedb-python#506). + +The engine's GraphBatch takes the RIDs of an edge on trust. A flush or close that gets a RID of no record, or of a document, +fails after the edge records are written, and no vertex then leads to any edge of the load. Both builds check the endpoints +before they buffer, so a refused call leaves nothing behind and the rest of the load stays whole. +""" + +import pytest + +import arcadedb +from arcadedb import ArcadeDBError + + +@pytest.fixture +def graph(tmp_path): + with arcadedb.create_database(str(tmp_path / "db")) as db: + db.command("sql", "CREATE VERTEX TYPE V") + db.command("sql", "CREATE EDGE TYPE E") + db.command("sql", "CREATE DOCUMENT TYPE D") + with db.transaction(): + db.command("sql", "INSERT INTO D SET n = 1") + yield db + + +def _count(db, query): + return db.query("sql", query).first().get("c") or 0 + + +def _bad_endpoint(db, kind, vertices): + bucket = vertices[0].split(":")[0] + if kind == "missing_position": + return bucket + ":99999" + if kind == "missing_bucket": + return "#999:0" + if kind == "document": + return db.query("sql", "SELECT FROM D").first().get_rid() + # an edge record: a RID that exists and is not a vertex + return db.query("sql", "SELECT FROM E").first().get_rid() + + +def _per_edge(batch, sources, destinations): + for source, destination in zip(sources, destinations): + batch.new_edge(source, "E", destination) + + +def _bulk(batch, sources, destinations): + batch.new_edges(sources, "E", destinations) + + +def _bulk_typed(batch, sources, destinations): + batch.new_edges(sources, "E", destinations, [{"w": 1} for _ in sources]) + + +def _bulk_text(batch, sources, destinations): + batch.new_edges(sources, "E", destinations, [{"w": [str(1)]} for _ in sources]) + + +@pytest.mark.parametrize("side", ["source", "destination"]) +@pytest.mark.parametrize( + "kind", ["missing_position", "missing_bucket", "document", "edge"] +) +@pytest.mark.parametrize("add", [_per_edge, _bulk, _bulk_typed, _bulk_text]) +def test_a_bad_endpoint_is_refused_and_the_rest_of_the_load_stays( + graph, add, kind, side +): + db = graph + with db.graph_batch() as batch: + vertices = batch.create_vertices("V", [{"n": i} for i in range(80)]) + batch.new_edge(vertices[70], "E", vertices[71]) + bad = _bad_endpoint(db, kind, vertices) + batch = db.graph_batch() + add(batch, vertices[:40], vertices[1:41]) + # 40 edges in the refused call (above the floor of the typed route), the bad one last: none of them may be buffered + sources, destinations = vertices[20:60], vertices[21:61] + (sources if side == "source" else destinations)[-1] = bad + if add is _per_edge: + sources, destinations = sources[-1:], destinations[-1:] + with pytest.raises(ArcadeDBError) as caught: + add(batch, sources, destinations) + assert bad in str(caught.value) + if kind.startswith("missing"): + assert caught.value.code == "record_not_found" + assert batch.get_buffered_edge_count() == 40 + batch.close() + edges = 41 # the one of the first batch and the 40 of the accepted call + assert _count(db, "SELECT count(*) AS c FROM E") == edges + assert _count(db, "SELECT sum(out('E').size()) AS c FROM V") == edges + assert _count(db, "SELECT sum(in('E').size()) AS c FROM V") == edges + + +def test_vertices_of_an_open_transaction_and_vertex_objects_are_accepted(graph): + db = graph + batch = db.graph_batch() + with db.transaction(): + first = db.command("sql", "CREATE VERTEX V SET n = 1").first().get_vertex() + second = db.command("sql", "CREATE VERTEX V SET n = 2").first().get_vertex() + batch.new_edge(first, "E", second) + batch.new_edges([second.get_rid()], "E", [first.get_rid()]) + batch.close() + assert _count(db, "SELECT sum(out('E').size()) AS c FROM V") == 2 + + +def test_a_deleted_vertex_is_refused(graph): + db = graph + with db.graph_batch() as batch: + vertices = batch.create_vertices("V", 3) + with db.transaction(): + db.command( + "sql", f"DELETE FROM {vertices[2]}" + ) # nosec B608 - a RID this test made + with db.graph_batch() as batch: + with pytest.raises(arcadedb.RecordNotFoundError): + batch.new_edge(vertices[0], "E", vertices[2])