diff --git a/docs/modules/ROOT/pages/how-to/bulk-loads.adoc b/docs/modules/ROOT/pages/how-to/bulk-loads.adoc index 8faec4a5..aa1ff0f7 100644 --- a/docs/modules/ROOT/pages/how-to/bulk-loads.adoc +++ b/docs/modules/ROOT/pages/how-to/bulk-loads.adoc @@ -315,8 +315,9 @@ Both arguments are bounds, not allocations you must reach: a batch that holds mo == Edge endpoints in a graph batch -// REMOVE WHEN: the endpoint check of ArcadeData/arcadedb-python#543 merges; its section replaces this one. -`GraphBatch.new_edge` and `GraphBatch.new_edges` do not check, on either package, that an endpoint is a vertex that exists (https://github.com/ArcadeData/arcadedb-python/issues/506[#506]). A RID of no record, or a RID of a document or an edge, is buffered like any other endpoint, and the error comes only at the flush or at `close()`: `RecordNotFoundError` for a RID of no record, and an `ArcadeDBError` for a document or an edge. By then the batch can already have written edge records that `out()` and `in()` do not reach, in the worst case every edge of the load. Pass vertices or RIDs that the load itself created or read, and check RIDs that come from elsewhere before you buffer edges to them. +`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 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..a28030bd --- /dev/null +++ b/tests/test_graph_batch_bad_endpoints.py @@ -0,0 +1,112 @@ +"""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(): + delete = f"DELETE FROM {vertices[2]}" # nosec B608 - a RID this test made + db.command("sql", delete) + with db.graph_batch() as batch: + with pytest.raises(arcadedb.RecordNotFoundError): + batch.new_edge(vertices[0], "E", vertices[2]) diff --git a/tests/test_graph_batch_typed_jvm.py b/tests/test_graph_batch_typed_jvm.py index 335c4882..3927e71f 100644 --- a/tests/test_graph_batch_typed_jvm.py +++ b/tests/test_graph_batch_typed_jvm.py @@ -42,7 +42,9 @@ def __getattr__(self, name): return attribute def call(*args): - self._log.append(name) + # the endpoint check (#506) is not a transport; these tests are about the transports + if not name.startswith("requireEndpoints"): + self._log.append(name) return attribute(*args) return call