From 3e7b48981da6cd062d6ad58075cd582e20a6e1ee Mon Sep 17 00:00:00 2001 From: Taewoon Kim Date: Sat, 14 Nov 2026 15:34:03 +0900 Subject: [PATCH 1/5] Tests: create_vertices and new_edges cross rows of exact scalars and float vectors as typed columns, RIDs back as a long[] (refs #388, #315) The crossing tests count VertexBatcher.createVerticesColumns and EdgeBatcher.newEdgesColumns calls per chunk, the parity tests store the same rows through the typed route and through the JSON text route (the typed route switched off) and compare the property order and the Java class and text of every stored value, and every shape the typed route cannot carry is pinned to the route it keeps. These fail on 26.11.1.post3, where neither bridge method exists. Co-Authored-By: Claude Sonnet 5.5 --- tests/conftest.py | 1 + tests/test_graph_batch_typed_jvm.py | 476 ++++++++++++++++++ .../test_graph_batch_vector_crossings_jvm.py | 16 +- 3 files changed, 485 insertions(+), 8 deletions(-) create mode 100644 tests/test_graph_batch_typed_jvm.py diff --git a/tests/conftest.py b/tests/conftest.py index fbd7008f..2d4ae4a7 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -162,6 +162,7 @@ "test_insert_many_gc_pause.py": "the cyclic collector pause is the JVM build's (the native insert_many allocates nothing the collector tracks)", "test_graph_batch_tagged_shapes.py": "the JVM wheel's graph batch bulk path (bridge VertexBatcher and EdgeBatcher, the property-matrix fallback)", "test_graph_batch_single_pass.py": "the JVM wheel's graph batch bulk path (GraphBatch._create_vertices_json_bulk, the property-matrix fallback)", + "test_graph_batch_typed_jvm.py": "the JVM wheel's typed graph batch route (bridge VertexBatcher.createVerticesColumns and EdgeBatcher.newEdgesColumns, JPype crossings, the Java classes of stored values)", "test_graph_batch_vector_crossings_jvm.py": "the JPype crossings of the JVM wheel's create_vertices vector path (the bridge classes, the property-matrix fallback)", "test_insert_columns_string_blob.py": "the bridge's StringColumn and the JVM wheel's core._column_to_java (JPype arrays, a spy on the per-element conversion)", "test_arrow_vector_column_jvm.py": "the JPype crossings of the JVM wheel's Arrow vector column (core.convert_python_to_java, the bridge's FloatVectors.Matrix) and its Python heap", diff --git a/tests/test_graph_batch_typed_jvm.py b/tests/test_graph_batch_typed_jvm.py new file mode 100644 index 00000000..c784a331 --- /dev/null +++ b/tests/test_graph_batch_typed_jvm.py @@ -0,0 +1,476 @@ +"""GraphBatch.create_vertices and new_edges (the JVM wheel): rows of exact scalars and float vectors cross as typed columns, not as JSON text (#388). + +Before, every chunk of rows crossed as one JSON text that the engine parsed into a JSONObject per row, and the created RIDs came back as one +';'-joined text. Now rows that are all dicts with the same keys in the same order, each property one kind of int, float, bool or str (None +for a null), and the float vectors of a declared or float32 property, cross as one typed column per property +(``VertexBatcher.createVerticesColumns``, ``EdgeBatcher.newEdgesColumns``), and the RIDs of the vertices come back as one ``long[]`` of +bucket id and position pairs. Every other shape keeps the JSON text path (or the property-matrix path), which these tests also pin. + +The parity tests store the same rows twice, once through the typed route and once with it switched off (``_scalar_columns`` answering None, +which is what every other shape gets), and compare what the engine holds: the property names in order, the Java class of each value and +its text. The JPype crossings are counted by wrapping the bridge classes. The JPype bridge does not exist on the native wheel, so +conftest.py does not collect this file there. +""" + +import jpype +import numpy as np +import pytest + +from arcadedb import graph_batch as gbm +from arcadedb import results as results_module +from arcadedb.graph_batch import GraphBatch + +CHUNK = 100 # rows per crossing in these tests: 250 rows are three crossings + + +class _Counting: + """Forwards every call of a Java class and records its name.""" + + def __init__(self, target, log): + self._target, self._log = target, log + + def __getattr__(self, name): + attribute = getattr(self._target, name) + if not callable(attribute): + return attribute + + def call(*args): + self._log.append(name) + return attribute(*args) + + return call + + +@pytest.fixture +def bridge(monkeypatch): + """The bridge calls of a load, by class, and the property-matrix fallbacks.""" + log = {"vertex": [], "edge": [], "matrix": []} + real_jclass = jpype.JClass + + def jclass(name, *args, **kwargs): + cls = real_jclass(name, *args, **kwargs) + if name == "com.arcadedb.python.VertexBatcher": + return _Counting(cls, log["vertex"]) + return cls + + monkeypatch.setattr(jpype, "JClass", jclass) + real_bridge_class = results_module._bridge_class + + def bridge_class(name): + cls = real_bridge_class(name) + if name == "EdgeBatcher" and cls is not None: + return _Counting(cls, log["edge"]) + return cls + + monkeypatch.setattr(results_module, "_bridge_class", bridge_class) + real_matrix = GraphBatch._to_java_property_matrix + + def matrix(self, rows): + log["matrix"].append(len(rows)) + return real_matrix(self, rows) + + monkeypatch.setattr(GraphBatch, "_to_java_property_matrix", matrix) + monkeypatch.setattr(GraphBatch, "_BULK_CHUNK", CHUNK) + return log + + +@pytest.fixture +def db(temp_db): + for name in ("A", "B", "VA", "VB", "VC"): + temp_db.command("sql", f"CREATE VERTEX TYPE {name}") + for name in ("EA", "EB"): + temp_db.command("sql", f"CREATE EDGE TYPE {name}") + for name in ("A", "B"): + temp_db.command("sql", f"CREATE PROPERTY {name}.embedding ARRAY_OF_FLOATS") + return temp_db + + +def _plain(value): + """A stored value as (Java class, text), or the list of the numbers of a float[]; None stays None.""" + if value is None: + return None + get_class = getattr(value, "getClass", None) + if get_class is None: # JPype handed over a Python value + return (type(value).__name__, repr(value)) + name = str(get_class().getName()) + if name.startswith("["): + return (name, [float(x) for x in value]) + return (name, str(value)) + + +def _stored(db, type_name): + """Every record of the type as its (property name, value) pairs in the order the engine holds them, sorted by id.""" + iterator = db._java_db.iterateType(type_name, False) + rows = [] + while iterator.hasNext(): + record = iterator.next().asDocument() + rows.append( + [(str(n), _plain(record.get(n))) for n in record.getPropertyNames()] + ) + rows.sort(key=lambda pairs: int(dict(pairs)["id"][1])) + return rows + + +INTS = [ + 0, + 1, + -1, + 2**31 - 1, + 2**31, + -(2**31), + -(2**31) - 1, + 2**53 + 1, + 2**63 - 1, + -(2**63), +] +_RNG = np.random.default_rng(11) +FLOATS = ( + [ + 0.0, + -0.0, + 1.5, + 0.1, + 1 / 3, + 1e300, + -1e-300, + 2.2250738585072014e-308, + 1e16, + 123456789.123456789, + ] + + [float(_RNG.uniform(-1e6, 1e6)) for _ in range(10)] + + [float(_RNG.random() ** 7) for _ in range(10)] +) +STRS = [ + "", + "a", + "héllo", + "\U0001f600 emoji", + "x" * 1000, + 'quote"s \\ back', + "nul\x00mid", + "line\nbreak", +] + + +def _scalar_rows(n=40): + rows = [] + for i in range(n): + rows.append( + { + "id": i, + "i": INTS[i % len(INTS)], + "f": FLOATS[i % len(FLOATS)], + "s": STRS[i % len(STRS)], + "b": i % 3 == 0, + "ni": None if i % 4 == 0 else i * 7, + "nf": None if i % 5 == 0 else i / 8, + "ns": None if i % 6 == 0 else f"v{i}", + "nb": None if i % 7 == 0 else i % 2 == 0, + "none": None, + } + ) + return rows + + +def _load(db, type_name, rows, **options): + with db.graph_batch(parallel_flush=False, **options) as gb: + return gb.create_vertices(type_name, rows) + + +# --------------------------------------------------------------------------- +# crossings: no JSON text for the shapes the typed route carries + + +def test_scalar_rows_cross_as_typed_columns_one_call_per_chunk(db, bridge): + rows = [ + {"id": i, "name": f"n{i}", "age": i % 90, "score": i / 4} for i in range(250) + ] + rids = _load(db, "A", rows) + assert len(rids) == 250 + assert bridge["vertex"] == ["createVerticesColumns"] * 3 # 100, 100, 50 + assert bridge["matrix"] == [] + + +def test_scalar_rows_with_a_vector_cross_as_typed_columns(db, bridge): + x = np.random.default_rng(3).standard_normal((250, 8)).astype(np.float32) + rows = [ + {"id": i, "views": i % 9, "embedding": jpype.JArray(jpype.JFloat)(x[i])} + for i in range(250) + ] + assert len(_load(db, "A", rows)) == 250 + assert bridge["vertex"] == ["createVerticesColumns"] * 3 + assert bridge["matrix"] == [] + + +def test_an_empty_batch_and_a_batch_of_one(db, bridge): + assert _load(db, "A", []) == [] + assert bridge["vertex"] == [] + one = _load(db, "A", [{"id": 1, "x": "y"}]) + assert len(one) == 1 and one[0].startswith("#") + assert bridge["vertex"] == ["createVerticesColumns"] + + +def test_rows_without_properties_cross_as_zero_columns(db, bridge): + rids = _load(db, "A", [{} for _ in range(7)]) + assert len(rids) == 7 and len(set(rids)) == 7 + assert bridge["vertex"] == ["createVerticesColumns"] + + +# --------------------------------------------------------------------------- +# the RIDs that come back + + +def test_the_rids_are_the_texts_in_row_order(db, bridge): + rows = [{"id": i} for i in range(250)] + rids = _load(db, "A", rows) + assert bridge["vertex"] == ["createVerticesColumns"] * 3 + assert all(type(rid) is str and rid.startswith("#") for rid in rids) + assert len(set(rids)) == 250 + by_rid = { + r["rid"]: r["id"] + for r in db.query("sql", "SELECT id, @rid AS rid FROM A").to_list() + } + assert [by_rid[str(rid)] for rid in rids] == list(range(250)) + + +def test_the_rids_equal_those_of_the_old_route(db, bridge, monkeypatch): + rows = [{"id": i, "s": f"v{i}"} for i in range(250)] + typed = _load(db, "A", rows) + monkeypatch.setattr(gbm, "_scalar_columns", lambda rows, reserved=(): None) + old = _load(db, "B", rows) + assert ( + bridge["vertex"] == ["createVerticesColumns"] * 3 + ["createVerticesJson"] * 3 + ) + assert len(typed) == len(old) == 250 and len(set(typed)) == len(set(old)) == 250 + assert all(type(rid) is str and rid.startswith("#") for rid in typed + old) + + +# --------------------------------------------------------------------------- +# parity: what the engine holds is what the old route stored + + +def test_every_scalar_kind_is_stored_as_the_old_route_stores_it( + db, bridge, monkeypatch +): + rows = _scalar_rows() + _load(db, "A", rows) + assert bridge["vertex"] == ["createVerticesColumns"] + monkeypatch.setattr(gbm, "_scalar_columns", lambda rows, reserved=(): None) + _load(db, "B", rows) + assert bridge["vertex"] == ["createVerticesColumns", "createVerticesJson"] + typed, old = _stored(db, "A"), _stored(db, "B") + assert len(typed) == len(old) == len(rows) + assert typed == old + + +def test_a_float_vector_among_scalars_is_stored_as_the_old_route_stores_it( + db, bridge, monkeypatch +): + x = np.random.default_rng(5).standard_normal((60, 8)).astype(np.float32) + rows = [ + { + "id": i, + "views": i % 11, + "embedding": jpype.JArray(jpype.JFloat)(x[i]), + "note": None if i % 3 else "n", + } + for i in range(60) + ] + _load(db, "A", rows) + monkeypatch.setattr(gbm, "_scalar_columns", lambda rows, reserved=(): None) + _load(db, "B", rows) + assert bridge["vertex"] == ["createVerticesColumns", "createVerticesJson"] + typed, old = _stored(db, "A"), _stored(db, "B") + assert len(typed) == 60 and typed == old + assert dict(typed[3])["embedding"][1] == [float(v) for v in x[3]] + + +def test_a_batch_of_one_and_a_load_over_the_chunk_boundary_agree( + db, bridge, monkeypatch +): + rows = _scalar_rows(250) + _load(db, "A", rows) + _load(db, "VA", rows[:1]) + monkeypatch.setattr(gbm, "_scalar_columns", lambda rows, reserved=(): None) + _load(db, "B", rows) + _load(db, "VB", rows[:1]) + assert _stored(db, "A") == _stored(db, "B") + assert _stored(db, "VA") == _stored(db, "VB") + + +def test_a_null_and_a_missing_key_stay_apart(db, bridge): + # rows with other keys keep the JSON text path: a missing key is no property, a None is a null, on both routes + rows = [{"id": 0, "x": None}, {"id": 1}, {"id": 2, "x": 5}] + _load(db, "A", rows) + assert bridge["vertex"] == ["createVerticesJson"] + stored = _stored(db, "A") + assert len(stored) == 3 + assert "x" not in dict(stored[1]) + assert dict(stored[2])["x"][1] == "5" + + +# --------------------------------------------------------------------------- +# the shapes the typed route keeps off, and where they go instead + + +@pytest.mark.parametrize( + "rows, route", + [ + ([{"id": 0, "a": 1}, {"id": 1}], "createVerticesJson"), # rows with other keys + ( + [{"id": 0, "a": 1, "b": 2}, {"id": 1, "b": 2, "a": 1}], + "createVerticesJson", + ), # another key order + ([{"id": 0}, None], "createVerticesJson"), # a row that is None + ([{"id": i, "l": ["a", i]} for i in range(3)], "createVerticesJson"), # a list + ([{"id": i, "m": {"k": i}} for i in range(3)], "createVerticesJson"), # a dict + ( + [{"id": 0, "x": 1}, {"id": 1, "x": 2.5}], + "createVerticesJson", + ), # ints beside floats + ( + [{"id": 0, "x": 1}, {"id": 1, "x": True}], + "createVerticesJson", + ), # an int beside a bool + ( + [{"id": 0, "x": np.int64(4)}], + None, + ), # a numpy scalar: the property-matrix path + ([{"id": 0, "x": float("nan")}], None), # a NaN + ([{"id": 0, "x": 5e-324}], None), # a subnormal + ], +) +def test_a_shape_the_typed_route_cannot_carry_keeps_the_old_routes( + db, bridge, rows, route +): + rids = _load(db, "A", rows) + assert len(rids) == len(rows) + assert "createVerticesColumns" not in bridge["vertex"] + if route is None: + assert bridge["vertex"] == [] and bridge["matrix"] == [len(rows)] + else: + assert bridge["vertex"] == [route] + + +def test_a_chunk_that_is_not_carried_does_not_move_the_others(db, bridge): + rows = [{"id": i, "v": i} for i in range(250)] + rows[120] = { + "id": 120, + "v": 2.5, + } # chunk 2 holds an int column with a float: that chunk keeps the text + rids = _load(db, "A", rows) + assert len(rids) == 250 + assert bridge["vertex"] == [ + "createVerticesColumns", + "createVerticesJson", + "createVerticesColumns", + ] + stored = {r["id"]: r["v"] for r in db.query("sql", "SELECT id, v FROM A").to_list()} + assert stored[119] == 119 and stored[120] == 2.5 and stored[121] == 121 + + +# --------------------------------------------------------------------------- +# edges + + +def _edge_setup(db, n=250): + vertices = _load(db, "VC", [{"id": i} for i in range(n)]) + return vertices + + +def _edge_props(n): + return [ + { + "id": i, + "w": INTS[i % len(INTS)], + "f": FLOATS[i % len(FLOATS)], + "s": STRS[i % len(STRS)], + "b": i % 3 == 0, + "n": None if i % 4 == 0 else i, + "z": None, + } + for i in range(n) + ] + + +def _new_edges(db, edge_type, sources, destinations, properties=None): + with db.graph_batch(parallel_flush=False) as gb: + gb.new_edges(sources, edge_type, destinations, properties) + + +def test_edge_properties_of_scalars_cross_as_typed_columns(db, bridge): + vertices = _edge_setup(db) + del bridge["vertex"][:] + sources, destinations = vertices, vertices[1:] + vertices[:1] + _new_edges(db, "EA", sources, destinations, _edge_props(250)) + assert bridge["edge"] == ["newEdgesColumns"] * 3 # 100, 100, 50 + assert len(_stored(db, "EA")) == 250 + + +def test_edges_without_a_property_value_in_any_dict_use_the_joined_call(db, bridge): + vertices = _edge_setup(db, 12) + _new_edges(db, "EA", vertices, vertices[1:] + vertices[:1], [{} for _ in vertices]) + _new_edges( + db, "EB", vertices, vertices[1:] + vertices[:1], [None for _ in vertices] + ) + assert bridge["edge"] == ["newEdgesJoined", "newEdgesJoined"] + assert db.query("sql", "SELECT count(*) AS n FROM EA").to_list()[0]["n"] == 12 + assert db.query("sql", "SELECT count(*) AS n FROM EB").to_list()[0]["n"] == 12 + + +def test_edge_properties_are_stored_as_the_old_route_stores_them( + db, bridge, monkeypatch +): + vertices = _edge_setup(db, 250) + sources, destinations = vertices, vertices[1:] + vertices[:1] + properties = _edge_props(250) + _new_edges(db, "EA", sources, destinations, properties) + monkeypatch.setattr(gbm, "_scalar_columns", lambda rows, reserved=(): None) + _new_edges(db, "EB", sources, destinations, properties) + assert bridge["edge"] == ["newEdgesColumns"] * 3 + ["newEdgesJson"] * 3 + typed, old = _stored(db, "EA"), _stored(db, "EB") + assert len(typed) == len(old) == 250 + assert typed == old + + +def test_a_batch_of_one_edge(db, bridge, monkeypatch): + vertices = _edge_setup(db, 2) + _new_edges(db, "EA", vertices[:1], vertices[1:], [{"id": 1, "w": 5}]) + monkeypatch.setattr(gbm, "_scalar_columns", lambda rows, reserved=(): None) + _new_edges(db, "EB", vertices[:1], vertices[1:], [{"id": 1, "w": 5}]) + assert bridge["edge"] == ["newEdgesColumns", "newEdgesJson"] + assert _stored(db, "EA") == _stored(db, "EB") and len(_stored(db, "EA")) == 1 + + +@pytest.mark.parametrize( + "properties", + [ + [{"id": 0, "a": 1}, {"id": 1}, {"id": 2, "a": 3}], # dicts with other keys + [{"id": 0}, None, {"id": 2}], # a None among dicts + [{"id": i, "l": ["a", i]} for i in range(3)], # a list + [ + {"id": 0, "x": 1}, + {"id": 1, "x": 2.5}, + {"id": 2, "x": 3}, + ], # ints beside floats + [ + {"id": i, "_src": "kept"} for i in range(3) + ], # a property named like a row's endpoint + ], +) +def test_edge_shapes_the_typed_route_cannot_carry_keep_the_old_routes( + db, bridge, properties +): + vertices = _edge_setup(db, 3) + _new_edges(db, "EA", vertices, vertices[1:] + vertices[:1], properties) + assert "newEdgesColumns" not in bridge["edge"] + assert len(_stored(db, "EA")) == 3 + + +def test_an_edge_chunk_that_is_not_carried_sends_the_whole_call_the_old_way(db, bridge): + vertices = _edge_setup(db, 250) + properties = [{"id": i, "v": i} for i in range(250)] + properties[120] = {"id": 120, "v": 2.5} + _new_edges(db, "EA", vertices, vertices[1:] + vertices[:1], properties) + assert "newEdgesColumns" not in bridge["edge"] + assert len(_stored(db, "EA")) == 250 diff --git a/tests/test_graph_batch_vector_crossings_jvm.py b/tests/test_graph_batch_vector_crossings_jvm.py index a86b89b9..ae000c28 100644 --- a/tests/test_graph_batch_vector_crossings_jvm.py +++ b/tests/test_graph_batch_vector_crossings_jvm.py @@ -5,7 +5,7 @@ builds one ``Object[]`` per row and one ``Object[][]`` for the call (an unwrapped Python loop that was 59 to 61 percent of the wall of the e2 and l3d loads in the untimed ingest profile of 26.11.1). A float32 numpy array on a property that is not declared ``ARRAY_OF_FLOATS`` took the same way. Now ``take_vector_columns`` stacks the column once (numpy reads a Java array through the buffer protocol), one -``float[]`` copy and one ``FloatVectors.Matrix`` cross per property, and one ``VertexBatcher.createVerticesJson`` call per chunk. +``float[]`` copy and one ``FloatVectors.Matrix`` cross per property, and one ``VertexBatcher.createVerticesColumns`` call per chunk. The JPype crossings are counted by wrapping the bridge classes and the Python-side conversion; the stored values are in test_vertex_vector_loads.py. The JPype bridge does not exist on the native wheel (its counts are in test_native_vertex_vector_crossings.py), @@ -129,7 +129,7 @@ def test_a_float32_vector_crosses_as_one_matrix_per_chunk( ), "the property-matrix path ran (a JPype conversion per value and per row)" assert crossings["convert"] == [], "a value was converted one at a time" assert ( - crossings["bridge"] == ["createVerticesJson"] * 3 + crossings["bridge"] == ["createVerticesColumns"] * 3 ) # one crossing per chunk of 100 # one float32 matrix per chunk: `declared` is asked once per call, `Matrix` once per chunk assert crossings["matrix"].count("Matrix") == 3 @@ -148,7 +148,7 @@ def test_two_vector_properties_cross_as_two_matrices_per_chunk(db, crossings): with db.graph_batch(parallel_flush=False) as gb: gb.create_vertices("Declared", rows) assert crossings["fallback"] == [] and crossings["convert"] == [] - assert crossings["bridge"] == ["createVerticesJson"] * 3 + assert crossings["bridge"] == ["createVerticesColumns"] * 3 assert crossings["matrix"].count("Matrix") == 6 @@ -162,7 +162,7 @@ def test_a_ragged_column_still_takes_the_property_matrix_path_for_its_chunk( with db.graph_batch(parallel_flush=False) as gb: assert len(gb.create_vertices("Declared", rows)) == ROWS assert crossings["fallback"] == [100], "only the chunk of row 120" - assert crossings["bridge"] == ["createVerticesJson"] * 2 + assert crossings["bridge"] == ["createVerticesColumns"] * 2 stored = { r["id"]: r["embedding"] for r in db.query("sql", "SELECT id, embedding FROM Declared").to_list() @@ -180,7 +180,7 @@ def test_a_java_double_array_is_a_vector_only_on_a_declared_property(db, crossin gb.create_vertices("Declared", rows) assert ( crossings["fallback"] == [] - and crossings["bridge"] == ["createVerticesJson"] * 3 + and crossings["bridge"] == ["createVerticesColumns"] * 3 ) declared = { r["id"]: r["embedding"] @@ -255,7 +255,7 @@ def test_rows_with_vectors_cross_in_blocks_sized_by_their_width( assert len(gb.create_vertices("Declared", rows)) == ROWS assert crossings["fallback"] == [] and crossings["convert"] == [] assert ( - crossings["bridge"] == ["createVerticesJson"] * 7 + crossings["bridge"] == ["createVerticesColumns"] * 7 ) # 6 blocks of 40, one of 10 assert crossings["matrix"].count("Matrix") == 7 sql = "SELECT id, embedding FROM Declared" @@ -269,12 +269,12 @@ def test_rows_with_vectors_cross_in_blocks_sized_by_their_width( rows = [{"id": 1000 + i, "embedding": arrays[i]} for i in range(25)] with db.graph_batch(parallel_flush=False) as gb: gb.create_vertices("Free", rows) - assert crossings["bridge"] == ["createVerticesJson"] * 3 # 10, 10, 5 + assert crossings["bridge"] == ["createVerticesColumns"] * 3 # 10, 10, 5 # rows without a vector keep the whole _BULK_CHUNK crossings["bridge"].clear() with db.graph_batch(parallel_flush=False) as gb: gb.create_vertices("Free", [{"id": 2000 + i} for i in range(ROWS)]) - assert crossings["bridge"] == ["createVerticesJson"] + assert crossings["bridge"] == ["createVerticesColumns"] def test_vector_width_counts_the_vector_columns_of_the_first_row(db): From 53802186b17d59f435ad696d5d61f1a0cbb64a7a Mon Sep 17 00:00:00 2001 From: Taewoon Kim Date: Sat, 14 Nov 2026 15:34:40 +0900 Subject: [PATCH 2/5] GraphBatch (JVM): create_vertices and new_edges send rows of exact scalars and float vectors as typed columns, and the RIDs come back as a long[] (refs #388, #315) VertexBatcher.createVerticesColumns and EdgeBatcher.newEdgesColumns take the layout of DocumentBatcher.insertColumns (long[], double[], boolean[], StringColumn, FloatVectors.Matrix, with null flags) and make the engine call the JSON text route made, with the same key and value per property. A long that fits an int is boxed as an Integer, as the engine's JSON parser did, so the stored class is unchanged. Rows that are not all dicts of the same keys in the same order, or hold a value other than one kind of int, float, bool or str per property, keep the JSON text route. Co-Authored-By: Claude Sonnet 5.5 --- .../modules/ROOT/pages/how-to/bulk-loads.adoc | 2 +- src/arcadedb/graph_batch.py | 169 +++++++++++++++++- .../com/arcadedb/python/DocumentBatcher.java | 2 +- src/java/com/arcadedb/python/EdgeBatcher.java | 25 +++ .../com/arcadedb/python/VertexBatcher.java | 67 +++++++ 5 files changed, 262 insertions(+), 3 deletions(-) diff --git a/docs/modules/ROOT/pages/how-to/bulk-loads.adoc b/docs/modules/ROOT/pages/how-to/bulk-loads.adoc index 7c10a805..a1506b2f 100644 --- a/docs/modules/ROOT/pages/how-to/bulk-loads.adoc +++ b/docs/modules/ROOT/pages/how-to/bulk-loads.adoc @@ -151,7 +151,7 @@ The `arcadedb` (native) package does not change the collector. In our measuremen == Property shapes in a graph batch (`arcadedb-jvm`) -On the `arcadedb-jvm` package, `GraphBatch.create_vertices` and `GraphBatch.new_edges` load these property values through the bulk path (the same tagged JSON text as `insert_many`): a list, a tuple, a dict, a `datetime`, a `date`, a `Decimal` and `bytes` (also `bytearray`). A value is stored as the one-by-one path stores it. A list or tuple of only `int` and `float` keeps the older path, which crosses it as one `double[]`. +On the `arcadedb-jvm` package, `GraphBatch.create_vertices` and `GraphBatch.new_edges` send rows whose properties are all `int`, `float`, `bool`, `str` or `None` (every row a `dict` with the same keys in the same order, each property one kind) as one typed column per property, with no JSON text, and `create_vertices` returns the RIDs from one `long[]` of bucket ids and positions. The values below, and any other rows, go through the bulk path (the same tagged JSON text as `insert_many`): a list, a tuple, a dict, a `datetime`, a `date`, a `Decimal` and `bytes` (also `bytearray`). A value is stored as the one-by-one path stores it. A list or tuple of only `int` and `float` keeps the older path, which crosses it as one `double[]`. A value that the text cannot carry sends work to the older path on its own. In `create_vertices`, a scalar that the text would change (a `NaN`, an integer beyond 64 bits, a lone surrogate, a subnormal float) sends the whole call to the older path, wherever in the input it sits. So does a property name that is not a `str`. A value inside a list or a dict that the text cannot carry (a `datetime` inside a list, a `NaN` in a list, a dict key that is not a `str`) sends only the chunk of at most 100,000 rows that holds it. `new_edges` falls back for the whole call. A value of another type (a `set`, a numpy or pandas value, a subclass of the types above) also takes the older path. diff --git a/src/arcadedb/graph_batch.py b/src/arcadedb/graph_batch.py index 8294f9ab..be31fdbc 100644 --- a/src/arcadedb/graph_batch.py +++ b/src/arcadedb/graph_batch.py @@ -4,6 +4,8 @@ Pythonic wrapper for ArcadeDB's high-throughput graph ingest API. """ +import itertools +import operator from typing import Any, Iterable, Optional import jpype @@ -12,6 +14,8 @@ from .exceptions import ArcadeDBError from .graph import Document, Vertex from .type_conversion import ( + _FLOAT_NORMAL_MIN, + _np, convert_python_to_java, declared_float_vectors, declared_scalars_ok, @@ -26,6 +30,108 @@ _LOGGER = get_logger(__name__) +_NONE_KIND = type(None) +# what a masked (null) row of a typed column holds: any value of the column's kind, never read +_FILL = {int: 0, float: 0.0, bool: False} + + +def _scalar_column(column): + """One column of exact scalars as ``(bridge column, bridge null flags or None)`` for ``VertexBatcher.createVerticesColumns`` and + ``EdgeBatcher.newEdgesColumns``, or None when the column is not one the typed route carries. + + Carried: every value of one exact type among ``int`` (in 64 bits, a ``long[]``), ``float`` (finite, no subnormal, a ``double[]``), + ``bool`` (a ``boolean[]``) and ``str`` (a ``StringColumn``, with its own null rows), with ``None`` for a null; a column of nothing + but ``None``. Anything else (mixed kinds, a bool beside ints, a subclass, a numpy scalar, a list, a date, a lone surrogate, an + integer beyond 64 bits, a NaN, an infinity or a subnormal) is left to the JSON text path, which stores or refuses it as before. + """ + n = len(column) + kinds = set(map(type, column)) + has_none = _NONE_KIND in kinds + kinds.discard(_NONE_KIND) + if not kinds: + return jpype.JArray(jpype.JBoolean)(_np.zeros(n, dtype=_np.bool_)), ( + jpype.JArray(jpype.JBoolean)(_np.ones(n, dtype=_np.bool_)) + ) + if len(kinds) != 1: + return None + (kind,) = kinds + if kind is str: + from .core import _string_column + + built = _string_column(column) + return None if built is None else (built, None) + if kind not in _FILL: + return None + mask = None + if has_none: + mask = _np.fromiter( + map(operator.is_, column, itertools.repeat(None)), dtype=_np.bool_, count=n + ) + fill = _FILL[kind] + column = [fill if value is None else value for value in column] + if kind is int: + try: + built = jpype.JArray(jpype.JLong)(_np.array(column, dtype=_np.int64)) + except OverflowError: + return None + elif kind is float: + array = _np.array(column, dtype=_np.float64) + if not _np.isfinite(array).all(): + return None + nonzero = array[array != 0.0] + if (_np.abs(nonzero) < _FLOAT_NORMAL_MIN).any(): + return None + built = jpype.JArray(jpype.JDouble)(array) + else: + built = jpype.JArray(jpype.JBoolean)(_np.array(column, dtype=_np.bool_)) + return built, None if mask is None else jpype.JArray(jpype.JBoolean)(mask) + + +def _scalar_columns(rows, reserved=()): + """The columns of ``rows`` for the typed route as ``(names, columns, null flags)`` (lists, one entry per property), or None. + + Carried: every row an exact ``dict`` with the same keys in the same order (str names, none of ``reserved``) and each column one + that ``_scalar_column`` carries. A row that is None or has other keys, another key order or any other value keeps the JSON text + path, which writes each row's own keys in its own order. Needs numpy, as every other typed route of the bindings does. + """ + if _np is None or not rows or set(map(type, rows)) != {dict}: + return None + shapes = set(map(tuple, rows)) + if len(shapes) != 1: + return None + (names,) = shapes + if not set(map(type, names)) <= {str} or any(name in reserved for name in names): + return None + columns = [] + nulls = [] + for name in names: + built = _scalar_column(list(map(operator.itemgetter(name), rows))) + if built is None: + return None + columns.append(built[0]) + nulls.append(built[1]) + return list(names), columns, nulls + + +def _bridge_columns(names, columns, nulls): + """``(String[], Object[], Object[] or None)`` for the bridge: the null flags cross only when some column has a null.""" + flags = ( + jpype.JArray(jpype.JObject)(nulls) + if any(flag is not None for flag in nulls) + else None + ) + return ( + jpype.JArray(jpype.JString)(names), + jpype.JArray(jpype.JObject)(columns), + flags, + ) + + +def _rids_from_pairs(packed): + """The RID texts (``"#12:345"``, what ``str(rid)`` gives) of a ``long[]`` of ``[bucket id, position]`` pairs.""" + numbers = _np.asarray(packed, dtype=_np.int64) + return list(map("#{}:{}".format, numbers[0::2].tolist(), numbers[1::2].tolist())) + class GraphBatch: """Wrapper for Java GraphBatch with builder-backed configuration. @@ -205,6 +311,14 @@ def create_vertices( per-element path stores it. A list of only numbers keeps the property-matrix path, which crosses it as one double[]. + Rows that are all dicts with the same keys in the same order, each property + holding one kind of ``int``, ``float``, ``bool`` or ``str`` (``None`` for a + null), plus the float vectors above, cross as one typed column per property, + and the RIDs come back as one ``long[]``: no JSON text on either side. Any + other rows (a row that is ``None``, rows with other keys, a list, dict, + date-time, date, Decimal or bytes value, a column of mixed kinds) cross as the + JSON text described above. The stored values are the same on both routes. + Large inputs cross in chunks of 100,000 rows on this build. On the native build (the ``arcadedb`` package) the chunk is the batch's ``commit_every``, 1000 unless ``graph_batch()`` got another value, and each chunk is its own transaction. Chunks that already went in stay stored if a later chunk fails. @@ -314,12 +428,28 @@ def dumps(chunk_rows): rids = [] for start in range(0, len(rows), step): # the previous chunk's rest rows, text and matrices go before this chunk's are built: two float[] buffers were alive at once - split = rest = text = None + split = rest = text = typed = names = columns = nulls = packed = None chunk = rows[start : start + step] split = split_float_vectors( self._java_db, type_name, chunk, declared, undeclared=True ) rest = split[0] if split else chunk + typed = _scalar_columns(rest) + if typed is not None: + # rows of exact scalars and float vectors: one typed column per property, the RIDs back as one long[] + names, columns, nulls = typed + if split: + names = names + [str(name) for name in split[1]] + columns = columns + list(split[2]) + nulls = nulls + [None] * len(split[2]) + packed = vertex_batcher.createVerticesColumns( + self._java_graph_batch, + type_name, + *_bridge_columns(names, columns, nulls), + len(chunk), + ) + rids.extend(_rids_from_pairs(packed)) + continue text = None if declared_scalars_ok(rest, declared): try: @@ -454,6 +584,9 @@ def new_edges( return self try: + 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 if properties is None: # One joined string crosses the boundary in a single bulk # copy; a Python list of N strings would be converted @@ -470,6 +603,23 @@ def new_edges( ) return self + typed = self._typed_edge_columns(properties) + 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 + edge_batcher.newEdgesColumns( + self._java_graph_batch, + ";".join(sources[start : start + step]), + edge_type, + ";".join(dests[start : start + step]), + *_bridge_columns(names, columns, nulls), + ) + return self + rows = [] tagged = False # a value that needs the tagged text; False keeps the untagged code of before for src, dst, p in zip(source_rids, destination_rids, properties): @@ -519,6 +669,23 @@ def new_edges( f"Failed to buffer batch edges '{edge_type}': {e}" ) from e + def _typed_edge_columns(self, properties): + """The typed columns of every chunk of the edge ``properties``, or None when any chunk is not carried. + + Every chunk is built before the first crosses, so a chunk the typed route cannot carry still sends the whole call down the + JSON text path with nothing buffered (as the tagged text is written before it crosses). A property named ``_src`` or ``_dst`` + stays on that path, where the rows hold the endpoints under those names. + """ + chunks = [] + for start in range(0, len(properties), self._BULK_CHUNK): + columns = _scalar_columns( + properties[start : start + self._BULK_CHUNK], ("_src", "_dst") + ) + if columns is None: + return None + chunks.append(columns) + return chunks + def flush(self) -> "GraphBatch": """Flush buffered edges to disk. diff --git a/src/java/com/arcadedb/python/DocumentBatcher.java b/src/java/com/arcadedb/python/DocumentBatcher.java index 8d892a91..ab4c254e 100644 --- a/src/java/com/arcadedb/python/DocumentBatcher.java +++ b/src/java/com/arcadedb/python/DocumentBatcher.java @@ -210,7 +210,7 @@ private static MutableDocument newRecord(final Database db, final String typeNam return vertex ? db.newVertex(typeName) : db.newDocument(typeName); } - private static void checkColumns(final String[] names, final Object[] columns, final int n) { + static void checkColumns(final String[] names, final Object[] columns, final int n) { final int k = names.length; if (columns.length != k) throw new IllegalArgumentException("columns has " + columns.length + " arrays for " + k + " names"); diff --git a/src/java/com/arcadedb/python/EdgeBatcher.java b/src/java/com/arcadedb/python/EdgeBatcher.java index e2152962..dd3ab529 100644 --- a/src/java/com/arcadedb/python/EdgeBatcher.java +++ b/src/java/com/arcadedb/python/EdgeBatcher.java @@ -42,6 +42,31 @@ public static void newEdgesJoined(final GraphBatch batch, final String joinedSou newEdges(batch, sources, edgeType, destinations); } + /** + * Bulk edges WITH properties as whole columns: the RIDs cross as the two joined texts of {@link #newEdgesJoined} and the property + * values as typed columns (see {@link VertexBatcher#createVerticesColumns}, which has the layout of {@code columns} and + * {@code nulls} and the boxing of an integer), one value per edge in each. Every edge gets the same property names, in the order of + * {@code names}; an empty {@code names} buffers edges without properties. The engine call is the one {@link #newEdgesJson} makes. + */ + public static void newEdgesColumns(final GraphBatch batch, final String joinedSourceRids, final String edgeType, + final String joinedDestinationRids, final String[] names, final Object[] columns, final Object[] nulls) { + final String[] sources = joinedSourceRids.split(";"); + final String[] destinations = joinedDestinationRids.split(";"); + if (sources.length != destinations.length) + throw new IllegalArgumentException( + "sourceRids and destinationRids must have the same length (" + sources.length + " vs " + destinations.length + ")"); + final int n = sources.length; + DocumentBatcher.checkColumns(names, columns, n); + VertexBatcher.checkNulls(names, nulls, n); + for (int i = 0; i < n; i++) { + final Object[] props = VertexBatcher.flatRow(names, columns, nulls, i); + if (props.length == 0) + batch.newEdge(new RID(sources[i]), edgeType, new RID(destinations[i])); + else + batch.newEdge(new RID(sources[i]), edgeType, new RID(destinations[i]), props); + } + } + /** * Bulk edges WITH properties: one JSON array of rows, each * {"_src": "#1:0", "_dst": "#1:1", ...properties}. Property values are JSON values and the tagged values diff --git a/src/java/com/arcadedb/python/VertexBatcher.java b/src/java/com/arcadedb/python/VertexBatcher.java index 5943f372..1c15c738 100644 --- a/src/java/com/arcadedb/python/VertexBatcher.java +++ b/src/java/com/arcadedb/python/VertexBatcher.java @@ -62,4 +62,71 @@ public static String createVerticesJson(final GraphBatch batch, final String typ } return sb.toString(); } + + /** + * Typed vertex creation: the rows arrive as whole columns (the layout of {@link DocumentBatcher#insertColumns}: a long[], a + * double[], a boolean[], a StringColumn, a FloatVectors.Matrix, ...) and cross once per column instead of as one JSON text, and the + * created RIDs go back as one long[] of 2 * n numbers, {@code [bucket id, position]} per vertex in row order, instead of one joined + * text. The engine call is the one {@link #createVerticesJson} makes, with the same key and value per property, so the stored + * records are the same: {@code names[c]} is the property of column c, in the order of the rows' keys; {@code nulls}, or its element + * c, is null when the column has no null, else one flag per row (a flagged row is set to null, as a JSON null is on the text path). + * A long that fits an int is boxed as an Integer and any other as a Long, because that is what the engine's JSON parser makes of + * the number token, and the text path stored it so. + */ + public static long[] createVerticesColumns(final GraphBatch batch, final String typeName, final String[] names, + final Object[] columns, final Object[] nulls, final int n) { + DocumentBatcher.checkColumns(names, columns, n); + checkNulls(names, nulls, n); + final Object[][] matrix = new Object[n][]; + for (int i = 0; i < n; i++) + matrix[i] = flatRow(names, columns, nulls, i); + final RID[] rids = batch.createVertices(typeName, matrix); + final long[] packed = new long[rids.length * 2]; + for (int i = 0; i < rids.length; i++) { + packed[2 * i] = rids[i].getBucketId(); + packed[2 * i + 1] = rids[i].getPosition(); + } + return packed; + } + + /** One flag array per name or none at all, each as long as the rows. */ + static void checkNulls(final String[] names, final Object[] nulls, final int n) { + if (nulls == null) + return; + if (nulls.length != names.length) + throw new IllegalArgumentException("nulls has " + nulls.length + " entries for " + names.length + " names"); + for (int c = 0; c < nulls.length; c++) + if (nulls[c] != null && (!(nulls[c] instanceof boolean[] flags) || flags.length != n)) + throw new IllegalArgumentException("the null flags of '" + names[c] + "' are not a boolean[] of " + n + " rows"); + } + + /** Row {@code i} as the engine's property varargs: name, value, name, value, ... (empty for a row without properties). */ + static Object[] flatRow(final String[] names, final Object[] columns, final Object[] nulls, final int i) { + final Object[] flat = new Object[names.length * 2]; + for (int c = 0; c < names.length; c++) { + flat[2 * c] = names[c]; + flat[2 * c + 1] = cell(columns[c], nulls == null ? null : (boolean[]) nulls[c], i); + } + return flat; + } + + private static Object cell(final Object column, final boolean[] nulls, final int i) { + if (nulls != null && nulls[i]) + return null; + if (column instanceof long[] a) { + final long v = a[i]; + return v >= Integer.MIN_VALUE && v <= Integer.MAX_VALUE ? (Object) Integer.valueOf((int) v) : (Object) Long.valueOf(v); + } + if (column instanceof double[] a) + return Double.valueOf(a[i]); + if (column instanceof boolean[] a) + return Boolean.valueOf(a[i]); + if (column instanceof StringColumn s) + return s.get(i); + if (column instanceof FloatVectors.Matrix m) + return m.row(i); + if (column instanceof TemporalColumn t) + return t.get(i); + return ((Object[]) column)[i]; + } } From 8bd2487a92b958933a7450cfbd88651d1d696fb6 Mon Sep 17 00:00:00 2001 From: Taewoon Kim Date: Sat, 14 Nov 2026 17:13:45 +0900 Subject: [PATCH 3/5] Tests: the returned RIDs are checked by the engine's lookup of each text, and the stored-record helper tolerates an edge without an id (refs #388) The first test read @rid back through SQL and looked the texts up in that dict, which did not hold them under the same keys; it now loads each returned RID through the database and compares the id. The edge shape test with a None among dicts has an edge without an id, which the helper's sort key did not allow for. Co-Authored-By: Claude Sonnet 5.5 --- tests/test_graph_batch_typed_jvm.py | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/tests/test_graph_batch_typed_jvm.py b/tests/test_graph_batch_typed_jvm.py index c784a331..648af0cd 100644 --- a/tests/test_graph_batch_typed_jvm.py +++ b/tests/test_graph_batch_typed_jvm.py @@ -107,7 +107,7 @@ def _stored(db, type_name): rows.append( [(str(n), _plain(record.get(n))) for n in record.getPropertyNames()] ) - rows.sort(key=lambda pairs: int(dict(pairs)["id"][1])) + rows.sort(key=lambda pairs: int(dict(pairs).get("id", (None, "-1"))[1])) return rows @@ -226,11 +226,13 @@ def test_the_rids_are_the_texts_in_row_order(db, bridge): assert bridge["vertex"] == ["createVerticesColumns"] * 3 assert all(type(rid) is str and rid.startswith("#") for rid in rids) assert len(set(rids)) == 250 - by_rid = { - r["rid"]: r["id"] - for r in db.query("sql", "SELECT id, @rid AS rid FROM A").to_list() - } - assert [by_rid[str(rid)] for rid in rids] == list(range(250)) + # the engine's own lookup of each returned text: row i must be the vertex that was created from rows[i] + rid_class = jpype.JClass("com.arcadedb.database.RID") + ids = [ + int(str(db._java_db.lookupByRID(rid_class(rid), True).asDocument().get("id"))) + for rid in rids + ] + assert ids == list(range(250)) def test_the_rids_equal_those_of_the_old_route(db, bridge, monkeypatch): From 4b64b81f9b0d265ead97226cb7e50c1ae5432fa7 Mon Sep 17 00:00:00 2001 From: Taewoon Kim Date: Mon, 23 Nov 2026 04:14:21 +0900 Subject: [PATCH 4/5] GraphBatch (JVM): the typed route keeps a floor, 512 rows for create_vertices and 32 edges for new_edges (refs #388, #315) The typed route builds the names array, the columns array and one bridge array per column on every call, and a StringColumn per str column, a fixed cost the JSON text does not have. A probe of both routes of this branch on the mini (cores 18 and 19, one process, the typed route forced off by making _scalar_columns answer None) found the typed route slower for a call of one row by 1.2 to 3.2 times for create_vertices and 1.5 to 3.8 times for new_edges. The crossovers differ by operation and shape. The first size where no probed shape is slower and none is slower above it is 32 edges for new_edges and 512 rows for create_vertices (the string-heavy l2 shapes are at 1.00 and 1.07 at 256 rows). A call of fewer rows (edges) keeps the old route, counted over the whole call and not per chunk, so a call over the floor crosses every one of its chunks typed. Edges with only empty property dicts keep newEdgesJoined at every size. The probe table is in the comment of the two constants. The routes of the calls below and at the floors are counted in new tests (never timed); the existing route tests switch the floors off, since they are about which shapes cross typed. The docs paragraph and the docstring of create_vertices say so. --- .../modules/ROOT/pages/how-to/bulk-loads.adoc | 2 +- src/arcadedb/graph_batch.py | 51 +++++-- tests/test_graph_batch_typed_jvm.py | 136 ++++++++++++++++++ .../test_graph_batch_vector_crossings_jvm.py | 2 + 4 files changed, 181 insertions(+), 10 deletions(-) diff --git a/docs/modules/ROOT/pages/how-to/bulk-loads.adoc b/docs/modules/ROOT/pages/how-to/bulk-loads.adoc index a1506b2f..9ae96ade 100644 --- a/docs/modules/ROOT/pages/how-to/bulk-loads.adoc +++ b/docs/modules/ROOT/pages/how-to/bulk-loads.adoc @@ -151,7 +151,7 @@ The `arcadedb` (native) package does not change the collector. In our measuremen == Property shapes in a graph batch (`arcadedb-jvm`) -On the `arcadedb-jvm` package, `GraphBatch.create_vertices` and `GraphBatch.new_edges` send rows whose properties are all `int`, `float`, `bool`, `str` or `None` (every row a `dict` with the same keys in the same order, each property one kind) as one typed column per property, with no JSON text, and `create_vertices` returns the RIDs from one `long[]` of bucket ids and positions. The values below, and any other rows, go through the bulk path (the same tagged JSON text as `insert_many`): a list, a tuple, a dict, a `datetime`, a `date`, a `Decimal` and `bytes` (also `bytearray`). A value is stored as the one-by-one path stores it. A list or tuple of only `int` and `float` keeps the older path, which crosses it as one `double[]`. +On the `arcadedb-jvm` package, `GraphBatch.create_vertices` and `GraphBatch.new_edges` send rows whose properties are all `int`, `float`, `bool`, `str` or `None` (every row a `dict` with the same keys in the same order, each property one kind) as one typed column per property, with no JSON text, and `create_vertices` returns the RIDs from one `long[]` of bucket ids and positions. This is so for a `create_vertices` call of at least 512 rows and a `new_edges` call of at least 32 edges: a smaller call keeps the JSON text, because the typed columns have a fixed cost per call that the text does not have. The values below, and any other rows, go through the bulk path (the same tagged JSON text as `insert_many`): a list, a tuple, a dict, a `datetime`, a `date`, a `Decimal` and `bytes` (also `bytearray`). A value is stored as the one-by-one path stores it. A list or tuple of only `int` and `float` keeps the older path, which crosses it as one `double[]`. A value that the text cannot carry sends work to the older path on its own. In `create_vertices`, a scalar that the text would change (a `NaN`, an integer beyond 64 bits, a lone surrogate, a subnormal float) sends the whole call to the older path, wherever in the input it sits. So does a property name that is not a `str`. A value inside a list or a dict that the text cannot carry (a `datetime` inside a list, a `NaN` in a list, a dict key that is not a `str`) sends only the chunk of at most 100,000 rows that holds it. `new_edges` falls back for the whole call. A value of another type (a `set`, a numpy or pandas value, a subclass of the types above) also takes the older path. diff --git a/src/arcadedb/graph_batch.py b/src/arcadedb/graph_batch.py index be31fdbc..b4d68c33 100644 --- a/src/arcadedb/graph_batch.py +++ b/src/arcadedb/graph_batch.py @@ -33,6 +33,30 @@ _NONE_KIND = type(None) # what a masked (null) row of a typed column holds: any value of the column's kind, never read _FILL = {int: 0, float: 0.0, bool: False} +# A call of fewer rows keeps the old route (the JSON text). The typed route has a fixed cost per call that the text does not have: +# the names array, the columns array, one bridge array per column and a StringColumn per str column, and the engine call is the same +# one. The floors come from a probe of both routes of this change (ArcadeData/arcadedb-python#391, 2026-11-23, one process, the +# efficiency cores 18 and 19 of the mini, a JVM of two processors, 300 to 1,500 calls per size and route in alternating blocks), with +# the typed route forced off by making _scalar_columns answer None. Time of one call on the typed route over the time on the text +# (below 1.00: the typed route is faster): +# +# create_vertices, rows per call: +# 1 8 16 64 128 256 512 1024 5000 +# 2 ints 1.30 1.53 1.34 1.13 1.03 0.96 0.92 0.87 0.84 +# l2: 2 int, 2 str 2.72 2.33 1.97 1.34 1.14 1.00 0.91 0.87 0.85 +# l2 with nulls 3.15 2.67 2.29 1.49 1.24 1.07 0.97 0.92 0.86 +# 7 props, 2 str 2.54 1.98 1.65 1.05 0.88 0.77 0.69 0.65 0.63 +# int, int, float[64] 1.21 1.17 1.10 0.99 0.93 0.91 0.87 0.88 0.87 +# +# new_edges, edges per call: +# 1 8 16 32 64 256 +# since (int) 1.55 1.11 0.82 0.62 0.45 0.35 +# int, float, str 3.79 1.86 1.32 0.87 0.62 0.39 +# +# The floor is the first size at which no probed shape is slower on the typed route and none is slower at the sizes above it. +# It counts the rows (edges) of the call, not of a chunk, so a call over the floor crosses every one of its chunks typed. +_TYPED_MIN_VERTICES = 512 +_TYPED_MIN_EDGES = 32 def _scalar_column(column): @@ -311,13 +335,15 @@ def create_vertices( per-element path stores it. A list of only numbers keeps the property-matrix path, which crosses it as one double[]. - Rows that are all dicts with the same keys in the same order, each property - holding one kind of ``int``, ``float``, ``bool`` or ``str`` (``None`` for a - null), plus the float vectors above, cross as one typed column per property, - and the RIDs come back as one ``long[]``: no JSON text on either side. Any - other rows (a row that is ``None``, rows with other keys, a list, dict, - date-time, date, Decimal or bytes value, a column of mixed kinds) cross as the - JSON text described above. The stored values are the same on both routes. + In a call of at least 512 rows, rows that are all dicts with the same keys in + the same order, each property holding one kind of ``int``, ``float``, ``bool`` + or ``str`` (``None`` for a null), plus the float vectors above, cross as one + typed column per property, and the RIDs come back as one ``long[]``: no JSON + text on either side. A smaller call keeps the JSON text, which costs less + than the fixed cost per call of the typed columns. Any other rows (a row that + is ``None``, rows with other keys, a list, dict, date-time, date, Decimal or + bytes value, a column of mixed kinds) cross as the JSON text described above. + The stored values are the same on both routes. Large inputs cross in chunks of 100,000 rows on this build. On the native build (the ``arcadedb`` package) the chunk is the batch's ``commit_every``, 1000 unless ``graph_batch()`` got another value, and each chunk is its own transaction. Chunks that @@ -426,6 +452,9 @@ def dumps(chunk_rows): max(self._VECTOR_BLOCK_MIN_ROWS, self._VECTOR_BLOCK_FLOATS // width), ) rids = [] + typed_ok = ( + len(rows) >= _TYPED_MIN_VERTICES + ) # a call below the floor keeps the text route (see _TYPED_MIN_VERTICES) for start in range(0, len(rows), step): # the previous chunk's rest rows, text and matrices go before this chunk's are built: two float[] buffers were alive at once split = rest = text = typed = names = columns = nulls = packed = None @@ -434,7 +463,7 @@ def dumps(chunk_rows): self._java_db, type_name, chunk, declared, undeclared=True ) rest = split[0] if split else chunk - typed = _scalar_columns(rest) + typed = _scalar_columns(rest) if typed_ok else None if typed is not None: # rows of exact scalars and float vectors: one typed column per property, the RIDs back as one long[] names, columns, nulls = typed @@ -603,7 +632,11 @@ def new_edges( ) return self - typed = self._typed_edge_columns(properties) + typed = ( + self._typed_edge_columns(properties) + if len(properties) >= _TYPED_MIN_EDGES + else None + ) 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] diff --git a/tests/test_graph_batch_typed_jvm.py b/tests/test_graph_batch_typed_jvm.py index 648af0cd..c2b885bb 100644 --- a/tests/test_graph_batch_typed_jvm.py +++ b/tests/test_graph_batch_typed_jvm.py @@ -21,6 +21,13 @@ from arcadedb.graph_batch import GraphBatch CHUNK = 100 # rows per crossing in these tests: 250 rows are three crossings +VFLOOR = ( + gbm._TYPED_MIN_VERTICES +) # the shipped floors: a call of fewer rows (edges) keeps the old route (see the last section) +EFLOOR = gbm._TYPED_MIN_EDGES +assert ( + VFLOOR >= 2 and EFLOOR >= 2 +), "the tests of the floors read a call of one row below it" class _Counting: @@ -41,6 +48,13 @@ def call(*args): return call +@pytest.fixture(autouse=True) +def _no_floor(monkeypatch): + """The tests before the last section are about which shapes cross typed, on calls of any size: both floors are off in them.""" + monkeypatch.setattr(gbm, "_TYPED_MIN_VERTICES", 1) + monkeypatch.setattr(gbm, "_TYPED_MIN_EDGES", 1) + + @pytest.fixture def bridge(monkeypatch): """The bridge calls of a load, by class, and the property-matrix fallbacks.""" @@ -476,3 +490,125 @@ def test_an_edge_chunk_that_is_not_carried_sends_the_whole_call_the_old_way(db, _new_edges(db, "EA", vertices, vertices[1:] + vertices[:1], properties) assert "newEdgesColumns" not in bridge["edge"] assert len(_stored(db, "EA")) == 250 + + +# --------------------------------------------------------------------------- +# the floors: a create_vertices call of fewer than _TYPED_MIN_VERTICES rows and a new_edges call of fewer than _TYPED_MIN_EDGES edges +# keep the old route (the typed route has a fixed cost per call that the text does not have; the probe that sets the values is in the +# comment of the constants). These tests count routes, they time nothing. + + +def _crossings(n): + return -(-n // CHUNK) + + +def _vector_rows(n): + x = np.random.default_rng(7).standard_normal((n, 8)).astype(np.float32) + return [ + {"id": i, "views": i % 11, "embedding": jpype.JArray(jpype.JFloat)(x[i])} + for i in range(n) + ] + + +@pytest.mark.parametrize("n", [1, VFLOOR - 1]) +def test_a_vertex_call_below_the_floor_takes_the_text_route_and_stores_the_same_records( + db, bridge, monkeypatch, n +): + rows = _scalar_rows(n) + monkeypatch.setattr(gbm, "_TYPED_MIN_VERTICES", VFLOOR) + assert len(_load(db, "A", rows)) == n + assert bridge["vertex"] == ["createVerticesJson"] * _crossings(n) + assert bridge["matrix"] == [] + monkeypatch.setattr(gbm, "_TYPED_MIN_VERTICES", 1) + assert len(_load(db, "B", rows)) == n + assert bridge["vertex"][_crossings(n) :] == ["createVerticesColumns"] * _crossings( + n + ) + stored = _stored(db, "A") + assert len(stored) == n and stored == _stored(db, "B") + + +@pytest.mark.parametrize("n", [VFLOOR, VFLOOR + 1]) +def test_a_vertex_call_of_the_floor_or_more_takes_the_typed_route( + db, bridge, monkeypatch, n +): + monkeypatch.setattr(gbm, "_TYPED_MIN_VERTICES", VFLOOR) + assert len(_load(db, "A", _scalar_rows(n))) == n + assert bridge["vertex"] == ["createVerticesColumns"] * _crossings(n) + assert bridge["matrix"] == [] + + +def test_the_vertex_floor_counts_the_rows_of_the_call_not_of_a_chunk( + db, bridge, monkeypatch +): + # a call of VFLOOR rows in four crossings: every chunk is below the floor, and every chunk crosses typed with the call + chunk = VFLOOR // 4 + 1 + monkeypatch.setattr(GraphBatch, "_BULK_CHUNK", chunk) + monkeypatch.setattr(gbm, "_TYPED_MIN_VERTICES", VFLOOR) + assert len(_load(db, "A", _scalar_rows(VFLOOR))) == VFLOOR + assert bridge["vertex"] == ["createVerticesColumns"] * -(-VFLOOR // chunk) + assert chunk < VFLOOR + # and a call of one row less is one text crossing per chunk, whatever the chunk + bridge["vertex"].clear() + assert len(_load(db, "B", _scalar_rows(VFLOOR - 1))) == VFLOOR - 1 + assert bridge["vertex"] == ["createVerticesJson"] * -(-(VFLOOR - 1) // chunk) + + +def test_vertices_with_a_vector_follow_the_floor_too(db, bridge, monkeypatch): + monkeypatch.setattr(gbm, "_TYPED_MIN_VERTICES", VFLOOR) + assert len(_load(db, "A", _vector_rows(VFLOOR - 1))) == VFLOOR - 1 + assert bridge["vertex"] == ["createVerticesJson"] * _crossings(VFLOOR - 1) + assert bridge["matrix"] == [] + bridge["vertex"].clear() + assert len(_load(db, "B", _vector_rows(VFLOOR))) == VFLOOR + assert bridge["vertex"] == ["createVerticesColumns"] * _crossings(VFLOOR) + assert len(_stored(db, "A")) == VFLOOR - 1 and len(_stored(db, "B")) == VFLOOR + + +@pytest.mark.parametrize("n", [1, EFLOOR - 1]) +def test_an_edge_call_below_the_floor_takes_the_text_route_and_stores_the_same_records( + db, bridge, monkeypatch, n +): + vertices = _edge_setup(db, n + 1) + sources, destinations = vertices[:n], vertices[1:] + properties = _edge_props(n) + monkeypatch.setattr(gbm, "_TYPED_MIN_EDGES", EFLOOR) + _new_edges(db, "EA", sources, destinations, properties) + assert bridge["edge"] == ["newEdgesJson"] * _crossings(n) + monkeypatch.setattr(gbm, "_TYPED_MIN_EDGES", 1) + _new_edges(db, "EB", sources, destinations, properties) + assert bridge["edge"][_crossings(n) :] == ["newEdgesColumns"] * _crossings(n) + typed, old = _stored(db, "EB"), _stored(db, "EA") + assert len(typed) == len(old) == n and typed == old + + +@pytest.mark.parametrize("n", [EFLOOR, EFLOOR + 1]) +def test_an_edge_call_of_the_floor_or_more_takes_the_typed_route( + db, bridge, monkeypatch, n +): + vertices = _edge_setup(db, n + 1) + monkeypatch.setattr(gbm, "_TYPED_MIN_EDGES", EFLOOR) + _new_edges(db, "EA", vertices[:n], vertices[1:], _edge_props(n)) + assert bridge["edge"] == ["newEdgesColumns"] * _crossings(n) + assert len(_stored(db, "EA")) == n + + +def test_the_edge_floor_counts_the_edges_of_the_call_not_of_a_chunk( + db, bridge, monkeypatch +): + chunk = EFLOOR // 2 + 1 + monkeypatch.setattr(GraphBatch, "_BULK_CHUNK", chunk) + vertices = _edge_setup(db, EFLOOR + 1) + monkeypatch.setattr(gbm, "_TYPED_MIN_EDGES", EFLOOR) + _new_edges(db, "EA", vertices[:EFLOOR], vertices[1:], _edge_props(EFLOOR)) + assert bridge["edge"] == ["newEdgesColumns"] * -(-EFLOOR // chunk) + assert chunk < EFLOOR + + +def test_the_floors_do_not_touch_edges_without_property_values(db, bridge, monkeypatch): + # [{}] * n is the call for edges without properties on every size: the floors are about the typed columns only + vertices = _edge_setup(db, 3) + monkeypatch.setattr(gbm, "_TYPED_MIN_EDGES", EFLOOR) + _new_edges(db, "EA", vertices[:2], vertices[1:], [{}, {}]) + assert bridge["edge"] == ["newEdgesJoined"] + assert len(_stored(db, "EA")) == 2 diff --git a/tests/test_graph_batch_vector_crossings_jvm.py b/tests/test_graph_batch_vector_crossings_jvm.py index ae000c28..b83406ad 100644 --- a/tests/test_graph_batch_vector_crossings_jvm.py +++ b/tests/test_graph_batch_vector_crossings_jvm.py @@ -45,6 +45,8 @@ def call(*args): @pytest.fixture def crossings(monkeypatch): """What the load does: property-matrix fallbacks, per-value conversions, bridge calls, Matrix constructions, per-row inserts.""" + # the floor of the typed route (tests/test_graph_batch_typed_jvm.py) is off: these tests count crossings of calls of 25 to 250 rows + monkeypatch.setattr(gbm, "_TYPED_MIN_VERTICES", 1) log = {"fallback": [], "convert": [], "bridge": [], "matrix": [], "per_row": []} real_matrix_path = GraphBatch._to_java_property_matrix From 5c04af32fb11826983c9d6d037ca3797b2bc959d Mon Sep 17 00:00:00 2001 From: Taewoon Kim Date: Mon, 23 Nov 2026 05:55:36 +0900 Subject: [PATCH 5/5] GraphBatch (JVM): a call the typed route cannot carry is refused before any column is built (refs #388, #315) The first timed run of the study (ab391-r1) found create_vertices of 5,000 rows with a list-valued property, above the floor, 6.9 percent slower than before (B/A 1.069 [1.058, 1.106], control 1.004): _scalar_columns checked the shapes of all rows, then built the bridge array of every column in order (a long[] for id, a StringColumn for name) and only at the tags column found the list that cannot be typed, and threw the arrays away. A probe on the mini (one process, the old and the new code side by side) put that at 3.1 to 3.3 ms per call of 5,000 rows. Now the first row is looked at first (a value of a type no typed column holds refuses the call there), then the types of every column are decided one after the other from the types alone (_column_kind), and only when every column is carried is a bridge array built (_build_column). A list in the first row, or in every row, costs 0.001 ms. A list in a late row costs one pass over the types, 1.1 ms per 5,000 rows (a third of before). A carried call costs what it did: 3.80 ms against 3.77 ms. What the typed route accepts and refuses is unchanged (_scalar_column keeps its contract as the two steps in a row). The cost below the edge floor (e_since_1 1.051, e_since_16 1.031) is not a scan: before the floor test new_edges runs only `not any(properties)` (it stops at the first dict that holds a property) and the length compare, 0.4 to 0.5 microseconds per call in one process with the three versions side by side on one glue jar; the rest of the 0.8 and 2 microseconds of the study is not in the Python code, so the order of the checks is left as it is. New tests count the calls that read and build columns (never time): a list in the first row builds nothing and reads no column, a list in a late row decides three columns and builds none, rows of another shape build none, a carried call decides and builds every column, a call below either floor reads no column. --- src/arcadedb/graph_batch.py | 79 ++++++++++++++----- tests/test_graph_batch_typed_jvm.py | 114 ++++++++++++++++++++++++++++ 2 files changed, 174 insertions(+), 19 deletions(-) diff --git a/src/arcadedb/graph_batch.py b/src/arcadedb/graph_batch.py index b4d68c33..2bb819c9 100644 --- a/src/arcadedb/graph_batch.py +++ b/src/arcadedb/graph_batch.py @@ -59,33 +59,41 @@ _TYPED_MIN_EDGES = 32 -def _scalar_column(column): - """One column of exact scalars as ``(bridge column, bridge null flags or None)`` for ``VertexBatcher.createVerticesColumns`` and - ``EdgeBatcher.newEdgesColumns``, or None when the column is not one the typed route carries. +# What a typed column can hold, besides None: one of these per column. A value of any other type (a list, a dict, a date-time, a Decimal, +# bytes, a numpy scalar, a subclass) keeps the call on the JSON text path, and the first row is enough to see that for most rows. +_TYPED_VALUE_TYPES = frozenset((int, float, bool, str, _NONE_KIND)) - Carried: every value of one exact type among ``int`` (in 64 bits, a ``long[]``), ``float`` (finite, no subnormal, a ``double[]``), - ``bool`` (a ``boolean[]``) and ``str`` (a ``StringColumn``, with its own null rows), with ``None`` for a null; a column of nothing - but ``None``. Anything else (mixed kinds, a bool beside ints, a subclass, a numpy scalar, a list, a date, a lone surrogate, an - integer beyond 64 bits, a NaN, an infinity or a subnormal) is left to the JSON text path, which stores or refuses it as before. + +def _column_kind(column): + """``(kind, has None)`` of one column the typed route can carry, else None, from the types of its values alone: no array is built. + + ``kind`` is ``int``, ``float``, ``bool`` or ``str``, or ``NoneType`` for a column of nothing but ``None``. """ - n = len(column) kinds = set(map(type, column)) has_none = _NONE_KIND in kinds kinds.discard(_NONE_KIND) if not kinds: - return jpype.JArray(jpype.JBoolean)(_np.zeros(n, dtype=_np.bool_)), ( - jpype.JArray(jpype.JBoolean)(_np.ones(n, dtype=_np.bool_)) - ) + return _NONE_KIND, has_none if len(kinds) != 1: return None (kind,) = kinds + return (kind, has_none) if kind in _FILL or kind is str else None + + +def _build_column(column, kind, has_none): + """``(bridge column, bridge null flags or None)`` of a column that ``_column_kind`` accepted, or None when its values cannot cross + unchanged (an integer beyond 64 bits, a NaN, an infinity, a subnormal, a lone surrogate): the JSON text path stores or refuses those. + """ + n = len(column) + if kind is _NONE_KIND: + return jpype.JArray(jpype.JBoolean)(_np.zeros(n, dtype=_np.bool_)), ( + jpype.JArray(jpype.JBoolean)(_np.ones(n, dtype=_np.bool_)) + ) if kind is str: from .core import _string_column built = _string_column(column) return None if built is None else (built, None) - if kind not in _FILL: - return None mask = None if has_none: mask = _np.fromiter( @@ -111,25 +119,58 @@ def _scalar_column(column): return built, None if mask is None else jpype.JArray(jpype.JBoolean)(mask) +def _scalar_column(column): + """One column of exact scalars as ``(bridge column, bridge null flags or None)`` for ``VertexBatcher.createVerticesColumns`` and + ``EdgeBatcher.newEdgesColumns``, or None when the column is not one the typed route carries. + + Carried: every value of one exact type among ``int`` (in 64 bits, a ``long[]``), ``float`` (finite, no subnormal, a ``double[]``), + ``bool`` (a ``boolean[]``) and ``str`` (a ``StringColumn``, with its own null rows), with ``None`` for a null; a column of nothing + but ``None``. Anything else (mixed kinds, a bool beside ints, a subclass, a numpy scalar, a list, a date, a lone surrogate, an + integer beyond 64 bits, a NaN, an infinity or a subnormal) is left to the JSON text path, which stores or refuses it as before. + """ + decided = _column_kind(column) + return None if decided is None else _build_column(column, *decided) + + def _scalar_columns(rows, reserved=()): """The columns of ``rows`` for the typed route as ``(names, columns, null flags)`` (lists, one entry per property), or None. Carried: every row an exact ``dict`` with the same keys in the same order (str names, none of ``reserved``) and each column one that ``_scalar_column`` carries. A row that is None or has other keys, another key order or any other value keeps the JSON text path, which writes each row's own keys in its own order. Needs numpy, as every other typed route of the bindings does. + + A call the typed route cannot carry pays little before it is refused: the first row is looked at first (a value of a type no typed + column holds, such as a list, refuses the call there), then the types of every column are decided one column after the other, and + only when all of them are carried is a bridge array built. """ - if _np is None or not rows or set(map(type, rows)) != {dict}: + if _np is None or not rows: return None - shapes = set(map(tuple, rows)) - if len(shapes) != 1: + first = rows[0] + if type(first) is not dict or not _TYPED_VALUE_TYPES.issuperset( + map(type, first.values()) + ): return None - (names,) = shapes + if set(map(type, rows)) != {dict}: + return None + names = tuple(first) if not set(map(type, names)) <= {str} or any(name in reserved for name in names): return None + decided = [] + try: + for name in names: + column = list(map(operator.itemgetter(name), rows)) + kind = _column_kind(column) + if kind is None: + return None + decided.append((column, kind)) + except KeyError: # a row without this key + return None + if len(set(map(tuple, rows))) != 1: + return None columns = [] nulls = [] - for name in names: - built = _scalar_column(list(map(operator.itemgetter(name), rows))) + for column, (kind, has_none) in decided: + built = _build_column(column, kind, has_none) if built is None: return None columns.append(built[0]) diff --git a/tests/test_graph_batch_typed_jvm.py b/tests/test_graph_batch_typed_jvm.py index c2b885bb..335c4882 100644 --- a/tests/test_graph_batch_typed_jvm.py +++ b/tests/test_graph_batch_typed_jvm.py @@ -612,3 +612,117 @@ def test_the_floors_do_not_touch_edges_without_property_values(db, bridge, monke _new_edges(db, "EA", vertices[:2], vertices[1:], [{}, {}]) assert bridge["edge"] == ["newEdgesJoined"] assert len(_stored(db, "EA")) == 2 + + +# --------------------------------------------------------------------------- +# the refusal is cheap: a call the typed route cannot carry reads the first row and the types of the columns, and builds no bridge array +# (the first timed run, ab391-r1, found create_vertices of 5,000 rows with a list-valued property 6.9 percent slower than before: the +# columns before the list were built and thrown away). These tests count the calls that read and build columns, they time nothing. + + +@pytest.fixture +def column_calls(monkeypatch): + """How often the types of a column were decided (``_column_kind``), a bridge array was built (``_build_column``), and + ``_scalar_columns`` and ``GraphBatch._typed_edge_columns`` ran.""" + log = {"kind": 0, "build": 0, "columns": 0, "edge_columns": 0} + + def counting(name, fn): + def wrapper(*args, **kwargs): + log[name] += 1 + return fn(*args, **kwargs) + + return wrapper + + monkeypatch.setattr(gbm, "_column_kind", counting("kind", gbm._column_kind)) + monkeypatch.setattr(gbm, "_build_column", counting("build", gbm._build_column)) + monkeypatch.setattr( + gbm, "_scalar_columns", counting("columns", gbm._scalar_columns) + ) + monkeypatch.setattr( + GraphBatch, + "_typed_edge_columns", + counting("edge_columns", GraphBatch._typed_edge_columns), + ) + return log + + +def _listed(n, at): + """n rows of {id, name, tags} where tags is a list in the rows of ``at`` and a str elsewhere.""" + return [ + {"id": i, "name": f"n{i}", "tags": ["a", f"t{i}"] if i in at else "x"} + for i in range(n) + ] + + +def test_a_list_in_the_first_row_is_refused_before_any_column_is_read( + db, bridge, column_calls, monkeypatch +): + monkeypatch.setattr(gbm, "_TYPED_MIN_VERTICES", VFLOOR) + rows = _listed(VFLOOR, range(VFLOOR)) + assert len(_load(db, "A", rows)) == VFLOOR + assert bridge["vertex"] == ["createVerticesJson"] * _crossings(VFLOOR) + assert column_calls["columns"] == _crossings(VFLOOR) # asked once per chunk + assert column_calls["kind"] == 0 and column_calls["build"] == 0 + stored = db.query("sql", "SELECT id, tags FROM A").to_list() + assert len(stored) == VFLOOR and all(len(r["tags"]) == 2 for r in stored) + + +@pytest.mark.parametrize("where", ["row_3_4", "last_row"]) +def test_a_list_in_a_late_row_is_refused_after_the_types_and_before_any_array( + db, column_calls, where +): + rows = _listed(VFLOOR, {3 * VFLOOR // 4} if where == "row_3_4" else {VFLOOR - 1}) + assert gbm._scalar_columns(rows) is None + # the types of id and name were decided, then those of tags, which refused; nothing was built + assert column_calls["kind"] == 3 and column_calls["build"] == 0 + + +def test_rows_with_another_shape_are_refused_before_any_array(db, column_calls): + rows = _listed(VFLOOR, set()) + rows[VFLOOR // 2] = {"id": 1, "name": "x"} # a row without a key + assert gbm._scalar_columns(rows) is None + assert column_calls["build"] == 0 + rows = _listed(VFLOOR, set()) + rows[VFLOOR // 2] = { + "id": 1, + "name": "x", + "tags": "y", + "more": 2, + } # a row with another key + assert gbm._scalar_columns(rows) is None + assert column_calls["build"] == 0 + rows = _listed(VFLOOR, set()) + rows[VFLOOR // 2] = {"name": "x", "id": 1, "tags": "y"} # another key order + assert gbm._scalar_columns(rows) is None + assert column_calls["build"] == 0 + + +def test_a_carried_call_decides_every_column_and_then_builds_every_column( + db, column_calls +): + rows = _scalar_rows(VFLOOR) + got = gbm._scalar_columns(rows) + assert got is not None and len(got[0]) == len(rows[0]) + assert column_calls["kind"] == len(rows[0]) == column_calls["build"] + + +def test_a_value_no_column_carries_in_the_first_row_is_found_by_the_first_row(): + for value in (["a"], {"k": 1}, b"x", np.int64(1), object()): + assert gbm._scalar_columns([{"id": 1, "v": value}] * 3) is None + + +def test_a_call_below_the_floors_reads_no_column(db, bridge, column_calls, monkeypatch): + monkeypatch.setattr(gbm, "_TYPED_MIN_VERTICES", VFLOOR) + monkeypatch.setattr(gbm, "_TYPED_MIN_EDGES", EFLOOR) + assert len(_load(db, "A", _scalar_rows(VFLOOR - 1))) == VFLOOR - 1 + vertices = _edge_setup(db, EFLOOR) + column_calls["columns"] = ( + 0 # the vertices of the setup are above the floor of vertices or not: only the edges count here + ) + _new_edges(db, "EA", vertices[: EFLOOR - 1], vertices[1:], _edge_props(EFLOOR - 1)) + assert column_calls["edge_columns"] == 0 and column_calls["columns"] == 0 + assert column_calls["kind"] == 0 and column_calls["build"] == 0 + _new_edges( + db, "EB", vertices[:EFLOOR], vertices[1:] + vertices[:1], _edge_props(EFLOOR) + ) + assert column_calls["edge_columns"] == 1 and column_calls["build"] > 0