From 33e0dcde56188a0ec59a157693ad97aea2f60adf Mon Sep 17 00:00:00 2001 From: Taewoon Kim Date: Fri, 27 Nov 2026 05:30:50 +0900 Subject: [PATCH 1/5] Native insert_many: store a whole number that fits an int as an Integer, as the JVM build does The engine's JSON reader types a whole number as an Integer when it fits an int and as a Long beyond, and the JVM build keeps that on both of its insert_many routes. The native build read every whole number as a Long, at the top level, inside lists and maps, and with parallel=True. The same rows had other stored types on the two packages, and a JSONL export of the native database was longer because it has to say which numbers are Long. The native library now narrows on the three routes insert_many uses (columns, JSON rows, parallel rows). A row that JSON text cannot carry keeps Long, as on the JVM build, and insert_columns still stores int64 columns as Long. A test reads the stored types through SQL on both wheels. --- .../modules/ROOT/pages/how-to/bulk-loads.adoc | 2 +- .../java/org/humemai/nativelib/BulkOps.java | 104 ++++++++++++++++-- .../org/humemai/nativelib/NativeExtras.java | 7 +- src/arcadedb/_native/bulk.py | 8 +- src/arcadedb/_native/columnar.py | 7 +- tests/test_insert_many_integer_types.py | 104 ++++++++++++++++++ tests/test_native_columnar_insert.py | 2 +- 7 files changed, 218 insertions(+), 16 deletions(-) create mode 100644 tests/test_insert_many_integer_types.py diff --git a/docs/modules/ROOT/pages/how-to/bulk-loads.adoc b/docs/modules/ROOT/pages/how-to/bulk-loads.adoc index 433db801..99549224 100644 --- a/docs/modules/ROOT/pages/how-to/bulk-loads.adoc +++ b/docs/modules/ROOT/pages/how-to/bulk-loads.adoc @@ -65,7 +65,7 @@ Because the two packages have different defaults, the same program can keep diff On both packages, `insert_many` keeps rows with `datetime`, `date`, `Decimal`, `bytes`, numpy scalar, or pandas `NA` and `NaT` values on the bulk path. On the `arcadedb` (native) package, a row with a value the bulk text cannot carry (NaN or infinity, an integer beyond 64 bits, a date-time or `Decimal` inside a list or dict, or a `datetime.time`) goes in with its own statement, in the order given. -On the `arcadedb-jvm` package, a chunk of rows (at most 10,000, at least 64) crosses as typed columns, with no JSON text, when every row is a `dict` with the same keys in the same order and each column holds `None` and values of one type: `int` within 64 bits, `float` (NaN and infinity included), `bool`, `str`, `date`, or a `datetime` without a time zone. The stored values are the same as the JSON text stores: a whole number is an `Integer` when it fits an int and a `Long` beyond, and `None` is a null property. A row with a NaN, an infinity, or a subnormal `float` stores its whole numbers as `Long`, which is what the per-row path stores for such a row. Any other chunk keeps the JSON text, as before: a row that lacks a key or lists the keys in another order, a column that mixes types (an `int` beside a `float`), a `Decimal`, `bytes`, numpy or pandas value, a `datetime` with a time zone, a list, tuple or dict, and a float vector for a property declared `ARRAY_OF_FLOATS`. A chunk is judged as a whole, so one such row sends its 10,000 rows down the JSON route. A chunk of fewer than 64 rows keeps the JSON text too (a call with a few rows, or the last rows of a load): the typed columns have a fixed cost per chunk, and below about 64 rows the text is the faster of the two. The `arcadedb` (native) package already sends the rows of one shape through its columnar entry. +On the `arcadedb-jvm` package, a chunk of rows (at most 10,000, at least 64) crosses as typed columns, with no JSON text, when every row is a `dict` with the same keys in the same order and each column holds `None` and values of one type: `int` within 64 bits, `float` (NaN and infinity included), `bool`, `str`, `date`, or a `datetime` without a time zone. The stored values are the same as the JSON text stores: a whole number is an `Integer` when it fits an int and a `Long` beyond, and `None` is a null property. A row with a NaN, an infinity, or a subnormal `float` stores its whole numbers as `Long`, which is what the per-row path stores for such a row. Any other chunk keeps the JSON text, as before: a row that lacks a key or lists the keys in another order, a column that mixes types (an `int` beside a `float`), a `Decimal`, `bytes`, numpy or pandas value, a `datetime` with a time zone, a list, tuple or dict, and a float vector for a property declared `ARRAY_OF_FLOATS`. A chunk is judged as a whole, so one such row sends its 10,000 rows down the JSON route. A chunk of fewer than 64 rows keeps the JSON text too (a call with a few rows, or the last rows of a load): the typed columns have a fixed cost per chunk, and below about 64 rows the text is the faster of the two. The `arcadedb` (native) package already sends the rows of one shape through its columnar entry, and it stores whole numbers as the same types: also inside a list or a dict, and also with `parallel=True`. `insert_columns` is another entry point and stores an `int64` column as `Long` on both packages. `insert_many` and `create_vertices` check their rows while they write the JSON text, in one pass over the rows, not in a loop before it. The same rows fail the check as before, and they take the same fallback path as before. The check raises no error to your code. diff --git a/native/src/main/java/org/humemai/nativelib/BulkOps.java b/native/src/main/java/org/humemai/nativelib/BulkOps.java index dcea786a..a762fcdf 100644 --- a/native/src/main/java/org/humemai/nativelib/BulkOps.java +++ b/native/src/main/java/org/humemai/nativelib/BulkOps.java @@ -107,7 +107,8 @@ static long handColumns(final Database db, final String type, final Map h, final long[] spec, final ErrorCallback onError) { final int commitEvery = ((Number) h.get("commit")).intValue(); + final boolean narrow = Boolean.TRUE.equals(h.get("narrow")); final Table table = Table.of(h, spec); final int n = table.n; final Object schemaType = db.getSchema().getType(type); @@ -131,7 +133,7 @@ private static long insertColumns(final Database db, final String type, final Ma try { for (; handed < n; handed++) { final MutableDocument doc = vertex ? db.newVertex(type) : db.newDocument(type); - setRow(doc, handed, table); + setRow(doc, handed, table, narrow); if (onError instanceof NativeExtras.RecordHooks hooks) hooks.submit(async, doc, handed); // an async create_record batch: each record has its own callbacks else @@ -145,7 +147,7 @@ private static long insertColumns(final Database db, final String type, final Ma } writeChunks(db, n, commitEvery, i -> { final MutableDocument doc = vertex ? db.newVertex(type) : db.newDocument(type); - setRow(doc, i, table); + setRow(doc, i, table, narrow); doc.save(); }); return n; @@ -219,10 +221,98 @@ private static void backoffBeforeRetry(final int attempt) { } } - /** Sets the properties of row i on doc from the columns. */ - private static void setRow(final MutableDocument doc, final int i, final Table t) { + /** + * Sets the properties of row i on doc from the columns. narrowIntegers (the header's "narrow", which insert_many sets): a whole number + * that fits an int is stored as an Integer, see {@link #narrowed}; without it the int64 columns stay Long, as insert_columns stores them. + */ + private static void setRow(final MutableDocument doc, final int i, final Table t, final boolean narrowIntegers) { + final boolean narrow = narrowIntegers && columnsCarriedByText(t, i); + for (int c = 0; c < t.k; c++) { + final Object v = t.cell(c, i); + doc.set(t.names[c], narrow && t.kinds[c] == 'q' ? narrowed(v) : v); + } + } + + /** + * Whether the JSON text route could have carried row i of the table: it cannot carry a NaN, an infinity or a subnormal float, so Python + * sends such a row through INSERT .. CONTENT on its own, which stores its whole numbers as Long. The columns keep that for such a row + * (as DocumentBatcher.carriedByText on the JVM build), so what a record stores does not depend on which route carried it. + */ + private static boolean columnsCarriedByText(final Table t, final int i) { for (int c = 0; c < t.k; c++) - doc.set(t.names[c], t.cell(c, i)); + if ((t.kinds[c] == 'd' || t.kinds[c] == 'e') && t.cell(c, i) instanceof Number x && !textDouble(x.doubleValue())) + return false; + return true; + } + + /** A double the JSON text keeps as a double: finite, and zero or at least the smallest normal value (Double.MIN_NORMAL). */ + private static boolean textDouble(final double v) { + return Double.isFinite(v) && (v == 0.0 || Math.abs(v) >= Double.MIN_NORMAL); + } + + /** + * The value a whole number takes through insert_many, as on the JVM build and as the engine's own JSON reader types it + * (JSONObject.parseNumber): an Integer when it fits an int, a Long beyond. Any other value is returned as it is. Written with returns, + * not a conditional: a conditional of an int and a long would promote both arms to long. + */ + static Object narrowed(final Object v) { + if (v instanceof Long l && l >= Integer.MIN_VALUE && l <= Integer.MAX_VALUE) + return Integer.valueOf(l.intValue()); + return v; + } + + /** A value of a parsed insert_many row: narrowed, and so are the whole numbers inside its lists and maps (changed in place). */ + @SuppressWarnings("unchecked") + static Object narrowedDeep(final Object v) { + if (v instanceof List) { + final List list = (List) v; + for (int k = 0; k < list.size(); k++) { + final Object element = list.get(k); + final Object stored = narrowedDeep(element); + if (stored != element) + list.set(k, stored); + } + return list; + } + if (v instanceof Map) { + for (final Map.Entry entry : ((Map) v).entrySet()) { + final Object element = entry.getValue(); + final Object stored = narrowedDeep(element); + if (stored != element) + entry.setValue(stored); + } + return v; + } + return narrowed(v); + } + + /** + * Whether the JSON text route of the JVM build could have carried this row of a parallel insert_many: no NaN, infinity or subnormal + * float anywhere in it, and no date, date-time, Decimal or byte array inside a list or map. The JVM build sends any other row down its + * per-row path, which stores its whole numbers as Long. + */ + static boolean rowCarriedByText(final Map row) { + for (final Object value : row.values()) + if (!valueCarriedByText(value, false)) + return false; + return true; + } + + private static boolean valueCarriedByText(final Object value, final boolean nested) { + if (value instanceof Double d) + return textDouble(d); + if (nested && (value instanceof LocalDate || value instanceof LocalDateTime || value instanceof BigDecimal || value instanceof byte[])) + return false; + if (value instanceof List list) { + for (final Object element : list) + if (!valueCarriedByText(element, true)) + return false; + } else if (value instanceof Map map) { + for (final Object element : map.values()) + if (!valueCarriedByText(element, true)) + return false; + } + return true; } /** @@ -423,7 +513,7 @@ static int insertRows(final Database db, final String type, final byte[] b, fina Json.rows(b, n, row -> { final MutableDocument doc = vertex ? db.newVertex(type) : db.newDocument(type); for (final Map.Entry e : row.entrySet()) - doc.set(e.getKey(), e.getValue()); + doc.set(e.getKey(), narrowedDeep(e.getValue())); doc.save(); count[0]++; }); diff --git a/native/src/main/java/org/humemai/nativelib/NativeExtras.java b/native/src/main/java/org/humemai/nativelib/NativeExtras.java index 92b8ac59..1b733477 100644 --- a/native/src/main/java/org/humemai/nativelib/NativeExtras.java +++ b/native/src/main/java/org/humemai/nativelib/NativeExtras.java @@ -1115,8 +1115,11 @@ else if (a.get("slot") instanceof Number slot) final boolean vertex = !rows.isEmpty() && isVertexType(db, type); for (final Object row : rows) { final MutableDocument doc = vertex ? db.newVertex(type) : db.newDocument(type); - for (final Map.Entry e : ((Map) row).entrySet()) - doc.set(e.getKey(), e.getValue()); + // whole numbers are typed as insert_many without parallel types them (BulkOps.narrowed) + final Map values = (Map) row; + final boolean narrow = BulkOps.rowCarriedByText(values); + for (final Map.Entry e : values.entrySet()) + doc.set(e.getKey(), narrow ? BulkOps.narrowedDeep(e.getValue()) : e.getValue()); ex.createRecord(doc, null, onError); } } catch (final Throwable t) { diff --git a/src/arcadedb/_native/bulk.py b/src/arcadedb/_native/bulk.py index 044e432d..0a8c42f9 100644 --- a/src/arcadedb/_native/bulk.py +++ b/src/arcadedb/_native/bulk.py @@ -23,7 +23,7 @@ def _usable(): ) -def _send(db, type_name, packed, rows, commit_every, prefix, fid=None): +def _send(db, type_name, packed, rows, commit_every, prefix, fid=None, narrow=False): from .database import _call spec = columnar.spec_of(packed) @@ -32,7 +32,7 @@ def _send(db, type_name, packed, rows, commit_every, prefix, fid=None): "arcadedb_n_insert_colp", db._h, lib.b(type_name), - lib.b(columnar.header_of(rows, commit_every, packed, fid)), + lib.b(columnar.header_of(rows, commit_every, packed, fid, narrow=narrow)), spec, len(spec), ) # `packed` holds the arrays the addresses point into until the call returns @@ -96,7 +96,9 @@ def insert_rows_columnar(db, type_name, chunk, declared=None): if packed is None: return False rows, cols = packed - _send(db, type_name, cols, rows, 0, f"Failed to bulk-insert into '{type_name}'") + prefix = f"Failed to bulk-insert into '{type_name}'" + # narrow: insert_many stores a whole number that fits an int as an Integer, as the JVM build does; insert_columns keeps Long + _send(db, type_name, cols, rows, 0, prefix, narrow=True) return True diff --git a/src/arcadedb/_native/columnar.py b/src/arcadedb/_native/columnar.py index 1fcfb8d7..551631cd 100644 --- a/src/arcadedb/_native/columnar.py +++ b/src/arcadedb/_native/columnar.py @@ -483,10 +483,11 @@ def spec_of(packed): return (ctypes.c_int64 * len(flat))(*flat) -def header_of(rows, commit_every, packed, fid=None, last=()): +def header_of(rows, commit_every, packed, fid=None, last=(), narrow=False): """The JSON header text: row count, commit interval and ``[name, kind, dim]`` per column; with a failure token ``fid`` it also says ``"parallel": true``, which hands the records to the async executor (the image then ignores the commit interval and counts the - failed records on that token). + failed records on that token). ``narrow`` (insert_many) adds ``"narrow": true``: the image then stores a whole number of an + int64 column that fits an int as an Integer, as the JVM build does. """ import json @@ -502,6 +503,8 @@ def header_of(rows, commit_every, packed, fid=None, last=()): if fid is not None: header["parallel"] = True header["fid"] = fid + if narrow: + header["narrow"] = True return json.dumps(header) diff --git a/tests/test_insert_many_integer_types.py b/tests/test_insert_many_integer_types.py new file mode 100644 index 00000000..a4309247 --- /dev/null +++ b/tests/test_insert_many_integer_types.py @@ -0,0 +1,104 @@ +"""insert_many stores a whole number as an Integer when it fits an int and as a Long beyond, on both builds (#445). + +That is how the engine's own JSON reader types a number. The native build used to store every whole number of an insert_many as a +Long, so the same Python rows had other stored types on the two packages, and a JSONL export of the native database was longer. A row +that JSON text cannot carry (a NaN, say) is the exception on both builds: it keeps its whole numbers as Long. ``insert_columns`` is not +``insert_many`` and stores an int64 column as Long on both builds. + +The stored type is read with the SQL method ``type()``. Nothing here depends on which build runs it. +""" + +import pytest + +INT_MIN, INT_MAX = -(2**31), 2**31 - 1 + + +def _type_of(db, type_name, expressions): + """For every record, in the order of ``id``: the stored type of each expression.""" + projection = ", ".join(f"{e}.type() AS t{n}" for n, e in enumerate(expressions)) + sql = f"SELECT id, {projection} FROM {type_name} ORDER BY id" # nosec B608 - test-owned names + return [ + [row.get(f"t{n}") for n in range(len(expressions))] + for row in db.query("sql", sql).to_list() + ] + + +@pytest.mark.parametrize("parallel", [False, True], ids=["transaction", "parallel"]) +@pytest.mark.parametrize("count", [3, 200], ids=["few-rows", "many-rows"]) +def test_whole_numbers_of_a_flat_row(temp_db, count, parallel): + temp_db.command("sql", "CREATE DOCUMENT TYPE Flat") + rows = [ + { + "id": i, + "lowest": INT_MIN, + "highest": INT_MAX, + "above": INT_MAX + 1, + "below": INT_MIN - 1, + "gaps": None if i % 3 == 0 else i, + "half": i / 2, + } + for i in range(count) + ] + assert temp_db.insert_many("Flat", rows, parallel=parallel) == count + + names = ["id", "lowest", "highest", "above", "below", "gaps", "half"] + stored = _type_of(temp_db, "Flat", names) + assert len(stored) == count + for i, types in enumerate(stored): + gaps = None if i % 3 == 0 else "INTEGER" + assert types == [ + "INTEGER", + "INTEGER", + "INTEGER", + "LONG", + "LONG", + gaps, + "DOUBLE", + ] + + +@pytest.mark.parametrize("parallel", [False, True], ids=["transaction", "parallel"]) +def test_whole_numbers_inside_a_list_and_a_map(temp_db, parallel): + temp_db.command("sql", "CREATE DOCUMENT TYPE Nested") + rows = [ + {"id": i, "lst": [1, 2**40], "obj": {"one": 1, "deep": [2, 2**40]}} + for i in range(3) + ] + assert temp_db.insert_many("Nested", rows, parallel=parallel) == 3 + + stored = _type_of( + temp_db, + "Nested", + ["lst[0]", "lst[1]", "obj.one", "obj.deep[0]", "obj.deep[1]"], + ) + assert stored == [["INTEGER", "LONG", "INTEGER", "INTEGER", "LONG"]] * 3 + read = temp_db.query("sql", "SELECT lst, obj FROM Nested WHERE id = 0").to_list() + assert read == [{"lst": [1, 2**40], "obj": {"one": 1, "deep": [2, 2**40]}}] + + +@pytest.mark.parametrize("parallel", [False, True], ids=["transaction", "parallel"]) +def test_a_row_json_cannot_carry_keeps_long(temp_db, parallel): + temp_db.command("sql", "CREATE DOCUMENT TYPE Odd") + rows = [ + {"id": 0, "n": 5, "x": float("nan")}, + {"id": 1, "n": 5, "x": 1.0}, + {"id": 2, "n": 5, "x": float("inf")}, + ] + assert temp_db.insert_many("Odd", rows, parallel=parallel) == 3 + + assert _type_of(temp_db, "Odd", ["id", "n"]) == [ + ["LONG", "LONG"], + ["INTEGER", "INTEGER"], + ["LONG", "LONG"], + ] + + +def test_a_declared_type_and_insert_columns_are_not_narrowed(temp_db): + temp_db.command("sql", "CREATE DOCUMENT TYPE Declared") + temp_db.command("sql", "CREATE PROPERTY Declared.wide LONG") + temp_db.insert_many("Declared", [{"id": i, "wide": i} for i in range(100)]) + assert _type_of(temp_db, "Declared", ["wide"]) == [["LONG"]] * 100 + + temp_db.command("sql", "CREATE DOCUMENT TYPE Columns") + temp_db.insert_columns("Columns", {"id": [0, 1], "n": [5, 6]}) + assert _type_of(temp_db, "Columns", ["id", "n"]) == [["LONG", "LONG"]] * 2 diff --git a/tests/test_native_columnar_insert.py b/tests/test_native_columnar_insert.py index 9b159f0b..dd95b151 100644 --- a/tests/test_native_columnar_insert.py +++ b/tests/test_native_columnar_insert.py @@ -271,7 +271,7 @@ def test_booleans_and_narrow_numpy_dtypes_keep_the_json_paths_types( "flag": ids % 3 == 0, "small": (ids - 150).astype(np.int32), # declared INTEGER: crosses as int32 "single": (ids / 8).astype(np.float32), # declared FLOAT: crosses as float32 - "narrow": ids.astype(np.int16), # undeclared: a Long, as from JSON + "narrow": ids.astype(np.int16), # undeclared: a whole number "half": (ids / 4).astype(np.float32), # undeclared: a Double, as from JSON } _json_reference(temp_db, "Ref", _rows(columns), monkeypatch) From 01b9b950acdfd0df9cf8955248ffbe74a467132d Mon Sep 17 00:00:00 2001 From: Taewoon Kim Date: Fri, 27 Nov 2026 05:37:07 +0900 Subject: [PATCH 2/5] Only insert_many narrows: the row path behind insert_columns and the DataFrame paths keeps Long On the native build a column set the buffers cannot carry goes down insert_many's row path. On the JVM build those entry points store Long, so the narrowing is now a flag that only insert_many sets, down to the JSON entry and the parallel writers. --- .../org/humemai/nativelib/ArcadeNative.java | 6 ++- .../java/org/humemai/nativelib/BulkOps.java | 4 +- .../org/humemai/nativelib/NativeExtras.java | 4 +- src/arcadedb/_native/bulk.py | 8 ++-- src/arcadedb/_native/database.py | 43 ++++++++++++------- src/arcadedb/_native/extras.py | 8 ++-- src/arcadedb/_native/lib.py | 2 +- tests/test_insert_many_integer_types.py | 9 ++++ tests/test_native_columnar_parallel.py | 4 +- 9 files changed, 57 insertions(+), 31 deletions(-) diff --git a/native/src/main/java/org/humemai/nativelib/ArcadeNative.java b/native/src/main/java/org/humemai/nativelib/ArcadeNative.java index 9e551a29..c8220887 100644 --- a/native/src/main/java/org/humemai/nativelib/ArcadeNative.java +++ b/native/src/main/java/org/humemai/nativelib/ArcadeNative.java @@ -825,14 +825,16 @@ public static CCharPointer execMany(final IsolateThread thread, final long h, fi /** * Documents (or vertices of a vertex type) from rows [{property: value},..], one record per row through newDocument/newVertex, set per * property and save, as DocumentBatcher.insertManyJson does on the JPype path; no transaction is opened or closed here. + * narrow (not 0, which insert_many passes): a whole number that fits an int is stored as an Integer (BulkOps.narrowed). */ @CEntryPoint(name = "arcadedb_n_insert_rows") - public static CCharPointer insertRows(final IsolateThread thread, final long h, final CCharPointer type, final CCharPointer rowsJson) { + public static CCharPointer insertRows(final IsolateThread thread, final long h, final CCharPointer type, final CCharPointer rowsJson, + final int narrow) { try { final Database db = db(h); final String t = str(type); final Chars c = chars(rowsJson); - return out("{\"ok\":true,\"n\":" + BulkOps.insertRows(db, t, c.b, c.n) + "}"); + return out("{\"ok\":true,\"n\":" + BulkOps.insertRows(db, t, c.b, c.n, narrow != 0) + "}"); } catch (final Throwable t) { return err(t); } diff --git a/native/src/main/java/org/humemai/nativelib/BulkOps.java b/native/src/main/java/org/humemai/nativelib/BulkOps.java index a762fcdf..7dd88818 100644 --- a/native/src/main/java/org/humemai/nativelib/BulkOps.java +++ b/native/src/main/java/org/humemai/nativelib/BulkOps.java @@ -507,13 +507,13 @@ Object cell(final int c, final int i) { * or closed here. The rows are parsed one at a time into one reused map (the property order of a fresh HashMap), so no tree of the * chunk and no String of the whole text is built. */ - static int insertRows(final Database db, final String type, final byte[] b, final int n) { + static int insertRows(final Database db, final String type, final byte[] b, final int n, final boolean narrow) { final boolean vertex = db.getSchema().getType(type) instanceof VertexType; final int[] count = new int[1]; Json.rows(b, n, row -> { final MutableDocument doc = vertex ? db.newVertex(type) : db.newDocument(type); for (final Map.Entry e : row.entrySet()) - doc.set(e.getKey(), narrowedDeep(e.getValue())); + doc.set(e.getKey(), narrow ? narrowedDeep(e.getValue()) : e.getValue()); doc.save(); count[0]++; }); diff --git a/native/src/main/java/org/humemai/nativelib/NativeExtras.java b/native/src/main/java/org/humemai/nativelib/NativeExtras.java index 1b733477..cddd925b 100644 --- a/native/src/main/java/org/humemai/nativelib/NativeExtras.java +++ b/native/src/main/java/org/humemai/nativelib/NativeExtras.java @@ -1115,9 +1115,9 @@ else if (a.get("slot") instanceof Number slot) final boolean vertex = !rows.isEmpty() && isVertexType(db, type); for (final Object row : rows) { final MutableDocument doc = vertex ? db.newVertex(type) : db.newDocument(type); - // whole numbers are typed as insert_many without parallel types them (BulkOps.narrowed) + // "narrow" (insert_many): whole numbers are typed as insert_many without parallel types them (BulkOps.narrowed) final Map values = (Map) row; - final boolean narrow = BulkOps.rowCarriedByText(values); + final boolean narrow = Boolean.TRUE.equals(a.get("narrow")) && BulkOps.rowCarriedByText(values); for (final Map.Entry e : values.entrySet()) doc.set(e.getKey(), narrow ? BulkOps.narrowedDeep(e.getValue()) : e.getValue()); ex.createRecord(doc, null, onError); diff --git a/src/arcadedb/_native/bulk.py b/src/arcadedb/_native/bulk.py index 0a8c42f9..797e88a6 100644 --- a/src/arcadedb/_native/bulk.py +++ b/src/arcadedb/_native/bulk.py @@ -80,12 +80,13 @@ def insert_columns_parallel(db, type_name, columns, declared=None): return db._finish_parallel(type_name, [fid], rows) -def insert_rows_columnar(db, type_name, chunk, declared=None): +def insert_rows_columnar(db, type_name, chunk, declared=None, narrow=False): """One ``insert_many`` chunk (a list of dicts with the same keys) through the columnar entry inside the caller's transaction (no commit here). Returns True when it was sent, False when the chunk needs the JSON path. ``declared``: the :class:`columnar.Declared` of the call, so that its chunks read the schema once between them (a chunk on its own - reads it when a column needs it). + reads it when a column needs it). ``narrow`` (insert_many): a whole number that fits an int is stored as an Integer; the + other callers of the row path (insert_columns, the DataFrame paths) leave it off and store Long, as on the JVM build. """ if not _usable(): return False @@ -97,8 +98,7 @@ def insert_rows_columnar(db, type_name, chunk, declared=None): return False rows, cols = packed prefix = f"Failed to bulk-insert into '{type_name}'" - # narrow: insert_many stores a whole number that fits an int as an Integer, as the JVM build does; insert_columns keeps Long - _send(db, type_name, cols, rows, 0, prefix, narrow=True) + _send(db, type_name, cols, rows, 0, prefix, narrow=narrow) return True diff --git a/src/arcadedb/_native/database.py b/src/arcadedb/_native/database.py index 59573010..3e0b6699 100644 --- a/src/arcadedb/_native/database.py +++ b/src/arcadedb/_native/database.py @@ -1162,18 +1162,25 @@ def insert_many( this build (the JVM build's is 10,000). Rows that are already committed stay committed if a later chunk fails, so a smaller ``commit_every`` keeps fewer rows of a failed load (only the transaction that was open is rolled back). """ - return self._insert_many(type_name, rows, commit_every, parallel) + return self._insert_many(type_name, rows, commit_every, parallel, narrow=True) def _insert_many( - self, type_name: str, rows, commit_every: int, parallel: bool, declared=None + self, + type_name: str, + rows, + commit_every: int, + parallel: bool, + declared=None, + narrow: bool = False, ) -> int: """:meth:`insert_many`, with the call's declared property types when an entry that ran before it already has them (``declared``: a ``columnar.Declared`` or a dict, see ``columnar.declared_for``). The chunks of the call share one, so the call - reads the schema once when a column needs the declared types, not once per chunk; it ends with the call. + reads the schema once when a column needs the declared types, not once per chunk; it ends with the call. ``narrow``: the call + is insert_many, which stores a whole number that fits an int as an Integer (the paths that fall back to this one do not). """ self._check_not_closed() if parallel: - return self._insert_many_parallel(type_name, rows) + return self._insert_many_parallel(type_name, rows, narrow) sql = f"INSERT INTO `{type_name}` CONTENT :row" declared = declared_for(self, type_name, declared) rows = iter(rows) @@ -1190,7 +1197,7 @@ def _insert_many( chunk = list(itertools.islice(rows, size)) if not chunk: break - self._insert_chunk(type_name, sql, declared, chunk) + self._insert_chunk(type_name, sql, declared, narrow, chunk) n += len(chunk) if not was_active and every > 0 and n % every == 0: self.commit() @@ -1207,7 +1214,9 @@ def _insert_many( pass raise - def _insert_chunk(self, type_name: str, sql: str, declared, chunk) -> None: + def _insert_chunk( + self, type_name: str, sql: str, declared, narrow: bool, chunk + ) -> None: """One chunk of ``insert_many`` inside the open transaction; see :meth:`insert_many` for the paths. ``declared`` is the ``columnar.Declared`` of the call, shared by its chunks. The chunk comes last: the ingest-integrity tests wrap this seam as ``(type_name, *lead, chunk)``. @@ -1217,30 +1226,33 @@ def _insert_chunk(self, type_name: str, sql: str, declared, chunk) -> None: every row is inserted in the order given. """ if lib.INSERT_ROWS: - if insert_rows_columnar(self, type_name, chunk, declared): + if insert_rows_columnar(self, type_name, chunk, declared, narrow): return try: payload = json_bulk_dumps_tagged(chunk) except (TypeError, ValueError): - self._insert_chunk_runs(type_name, sql, declared, chunk) + self._insert_chunk_runs(type_name, sql, declared, narrow, chunk) return - self._insert_rows_json(type_name, payload) + self._insert_rows_json(type_name, payload, narrow) return self._insert_chunk_per_row(sql, chunk) - def _insert_rows_json(self, type_name: str, payload: str) -> None: + def _insert_rows_json(self, type_name: str, payload: str, narrow: bool) -> None: reply = json.loads( lib.call( "arcadedb_n_insert_rows", self._h, lib.b(type_name), lib.b(payload), + int(narrow), ) ) if not reply.get("ok"): raise _error(f"Failed to bulk-insert into '{type_name}'", reply) - def _insert_chunk_runs(self, type_name: str, sql: str, declared, chunk) -> None: + def _insert_chunk_runs( + self, type_name: str, sql: str, declared, narrow: bool, chunk + ) -> None: """A chunk with a row the JSON text cannot carry: runs of carriable rows go in bulk, the other rows one statement each, in order.""" ok = [bulk_row_ok(row) for row in chunk] n = len(chunk) @@ -1254,8 +1266,8 @@ def _insert_chunk_runs(self, type_name: str, sql: str, declared, chunk) -> None: start = end if not carriable: self._insert_chunk_per_row(sql, run) - elif not insert_rows_columnar(self, type_name, run, declared): - self._insert_rows_json(type_name, json_bulk_dumps_tagged(run)) + elif not insert_rows_columnar(self, type_name, run, declared, narrow): + self._insert_rows_json(type_name, json_bulk_dumps_tagged(run), narrow) def _insert_chunk_per_row(self, sql: str, rows) -> None: if lib.EXEC_MANY: @@ -1332,7 +1344,7 @@ def _parallel_load_failed(self, type_name, error, tokens=()) -> ArcadeDBError: f"for them before raising)" ) - def _insert_many_parallel(self, type_name, rows) -> int: + def _insert_many_parallel(self, type_name, rows, narrow=False) -> int: """insert_many(parallel=True): chunks go to the async writers; the failure count is read after the final wait.""" import itertools @@ -1346,7 +1358,8 @@ def _insert_many_parallel(self, type_name, rows) -> int: if not chunk: break try: - tokens.append(extras.insert_parallel(self, type_name, chunk)["fid"]) + reply = extras.insert_parallel(self, type_name, chunk, narrow) + tokens.append(reply["fid"]) except ArcadeDBError as e: # as the JPype path: the rows handed to the writers before the failure are written whatever this call does raise self._parallel_load_failed(type_name, e, tokens) from e diff --git a/src/arcadedb/_native/extras.py b/src/arcadedb/_native/extras.py index ad070078..f6ae3ff6 100644 --- a/src/arcadedb/_native/extras.py +++ b/src/arcadedb/_native/extras.py @@ -1268,14 +1268,16 @@ def close(self): owner._discard_async_executor(self) -def insert_parallel(database, type_name: str, rows) -> dict: - """Hand ``rows`` (a list of dicts) to the async writers; returns the failure token for :func:`failures`.""" +def insert_parallel(database, type_name: str, rows, narrow: bool = False) -> dict: + """Hand ``rows`` (a list of dicts) to the async writers; returns the failure token for :func:`failures`. ``narrow`` + (insert_many): a whole number that fits an int is stored as an Integer. + """ return _call( "Failed to bulk-insert", "arcadedb_n_async", database._h, b"insert_parallel", - lib.b(_enc({"type": type_name, "rows": rows})), + lib.b(_enc({"type": type_name, "rows": rows, "narrow": narrow})), ) diff --git a/src/arcadedb/_native/lib.py b/src/arcadedb/_native/lib.py index c2781b0e..90ca6911 100644 --- a/src/arcadedb/_native/lib.py +++ b/src/arcadedb/_native/lib.py @@ -259,7 +259,7 @@ class _Params(ctypes.Structure): "arcadedb_n_last_error": [P], "arcadedb_n_rs_close_many": [P, P, N], "arcadedb_n_exec_many": [P, L, S, S, S], - "arcadedb_n_insert_rows": [P, L, S, S], + "arcadedb_n_insert_rows": [P, L, S, S, N], "arcadedb_n_server_start": [P, S], "arcadedb_n_server_stop": [P, L], "arcadedb_n_server_db": [P, L, S, N], diff --git a/tests/test_insert_many_integer_types.py b/tests/test_insert_many_integer_types.py index a4309247..26d71457 100644 --- a/tests/test_insert_many_integer_types.py +++ b/tests/test_insert_many_integer_types.py @@ -102,3 +102,12 @@ def test_a_declared_type_and_insert_columns_are_not_narrowed(temp_db): temp_db.command("sql", "CREATE DOCUMENT TYPE Columns") temp_db.insert_columns("Columns", {"id": [0, 1], "n": [5, 6]}) assert _type_of(temp_db, "Columns", ["id", "n"]) == [["LONG", "LONG"]] * 2 + + +@pytest.mark.parametrize("parallel", [False, True], ids=["transaction", "parallel"]) +def test_insert_columns_with_a_nested_column_keeps_long(temp_db, parallel): + """A column the native buffers cannot carry sends insert_columns down the row path, which must not change its stored types.""" + temp_db.command("sql", "CREATE DOCUMENT TYPE Mixed") + columns = {"id": [0, 1], "n": [5, 6], "tags": [["a"], ["b", "c"]]} + temp_db.insert_columns("Mixed", columns, parallel=parallel) + assert _type_of(temp_db, "Mixed", ["id", "n"]) == [["LONG", "LONG"]] * 2 diff --git a/tests/test_native_columnar_parallel.py b/tests/test_native_columnar_parallel.py index 90d6f79a..f11191fa 100644 --- a/tests/test_native_columnar_parallel.py +++ b/tests/test_native_columnar_parallel.py @@ -28,9 +28,9 @@ def call(name, *args): self.calls.append(name) return real_call(name, *args) - def insert_parallel(database, type_name, rows): + def insert_parallel(database, type_name, rows, *flags): self.row_chunks += 1 - return real_rows(database, type_name, rows) + return real_rows(database, type_name, rows, *flags) monkeypatch.setattr(lib, "call", call) monkeypatch.setattr(extras, "insert_parallel", insert_parallel) From b77e09c53809e43cffecafbb3b4cb5d9469238cd Mon Sep 17 00:00:00 2001 From: Taewoon Kim Date: Fri, 27 Nov 2026 05:54:17 +0900 Subject: [PATCH 3/5] Upgrade page: the stored type of a whole number from insert_many on the native package --- docs/modules/ROOT/pages/upgrading.adoc | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/docs/modules/ROOT/pages/upgrading.adoc b/docs/modules/ROOT/pages/upgrading.adoc index 1bf4420f..d0554305 100644 --- a/docs/modules/ROOT/pages/upgrading.adoc +++ b/docs/modules/ROOT/pages/upgrading.adoc @@ -8,7 +8,7 @@ ifdef::env-github[] :jvm-pkg-name: arcadedb-jvm endif::[] -// Sources: the pull requests ArcadeData/arcadedb-python #479 to #483, and the change of issue #454. Pinned by tests/test_auto_transaction_default.py, tests/test_error_codes_table.py, tests/test_error_codes_parity.py, tests/test_lazy_import.py and tests/test_cross_wheel_golden.py. +// Sources: the pull requests ArcadeData/arcadedb-python #479 to #483, and the changes of issues #454 and #445. Pinned by tests/test_auto_transaction_default.py, tests/test_error_codes_table.py, tests/test_error_codes_parity.py, tests/test_lazy_import.py tests/test_cross_wheel_golden.py and tests/test_insert_many_integer_types.py. Read this page before you move a program from 26.11.1, or from one of its post releases, to 26.12.1. It covers both packages, `{native-pkg-name}` and `{jvm-pkg-name}`. The changes of the engine itself are listed with the https://github.com/ArcadeData/arcadedb/releases[releases of ArcadeDB]. @@ -41,6 +41,10 @@ See xref:how-to/errors.adoc[Errors: codes, hints and classes]. Before, `{native-pkg-name}` wrote every character outside ASCII as a `\u` escape. Now it writes the character itself, as `{jvm-pkg-name}` does, and keeps an escape only for control characters, U+2028 and U+2029. The parsed values are the same. Only the text, and so its length, its bytes and a hash of it, differs from what `{native-pkg-name}` returned before. +=== `{native-pkg-name}` stores a whole number from `insert_many` as `{jvm-pkg-name}` does + +Before, `{native-pkg-name}` stored every whole number that `insert_many` wrote as a `Long`. Now it stores an `Integer` when the number fits 32 bits, also inside a list or a dict, and a `Long` beyond that, as `{jvm-pkg-name}` does. A property that the type declares keeps its declared type, the values that Python reads back are the same, and records that are already stored do not change. Code that asks for the stored type, for example with the SQL method `type()`, can see `INTEGER` where it saw `LONG`. See xref:how-to/bulk-loads.adoc[Bulk loads and commit size]. + === Engine 26.12.1 The engine that the 26.12.1 packages carry changes some behaviour that the other pages describe: From ba0d03b4194da6b91bbb8a68bc4af969c72d1064 Mon Sep 17 00:00:00 2001 From: Taewoon Kim Date: Fri, 27 Nov 2026 05:54:26 +0900 Subject: [PATCH 4/5] Tests: say which types the native columnar tests compare --- docs/modules/ROOT/pages/upgrading.adoc | 2 +- tests/test_native_columnar_insert.py | 3 +++ tests/test_native_columnar_parallel.py | 3 +++ 3 files changed, 7 insertions(+), 1 deletion(-) diff --git a/docs/modules/ROOT/pages/upgrading.adoc b/docs/modules/ROOT/pages/upgrading.adoc index d0554305..2a77bfa3 100644 --- a/docs/modules/ROOT/pages/upgrading.adoc +++ b/docs/modules/ROOT/pages/upgrading.adoc @@ -8,7 +8,7 @@ ifdef::env-github[] :jvm-pkg-name: arcadedb-jvm endif::[] -// Sources: the pull requests ArcadeData/arcadedb-python #479 to #483, and the changes of issues #454 and #445. Pinned by tests/test_auto_transaction_default.py, tests/test_error_codes_table.py, tests/test_error_codes_parity.py, tests/test_lazy_import.py tests/test_cross_wheel_golden.py and tests/test_insert_many_integer_types.py. +// Sources: the pull requests ArcadeData/arcadedb-python #479 to #483, and the changes of issues #454 and #445. Pinned by tests/test_auto_transaction_default.py, tests/test_error_codes_table.py, tests/test_error_codes_parity.py, tests/test_lazy_import.py, tests/test_cross_wheel_golden.py and tests/test_insert_many_integer_types.py. Read this page before you move a program from 26.11.1, or from one of its post releases, to 26.12.1. It covers both packages, `{native-pkg-name}` and `{jvm-pkg-name}`. The changes of the engine itself are listed with the https://github.com/ArcadeData/arcadedb/releases[releases of ArcadeDB]. diff --git a/tests/test_native_columnar_insert.py b/tests/test_native_columnar_insert.py index dd95b151..d0e971eb 100644 --- a/tests/test_native_columnar_insert.py +++ b/tests/test_native_columnar_insert.py @@ -4,6 +4,9 @@ scripts/check_test_skips.py). Each test loads the same data through the JSON path (``bulk._ENABLED`` off) and through the columnar entry and compares the stored records value by value and type by type; a spy on the crossing proves which entry point ran, so a silent fall back to JSON cannot pass for the columnar path. + +The types compared are the Python types read back. insert_many stores a whole number that fits an int as an Integer and +insert_columns as a Long (tests/test_insert_many_integer_types.py), and both read back as int. """ import ctypes diff --git a/tests/test_native_columnar_parallel.py b/tests/test_native_columnar_parallel.py index f11191fa..38881444 100644 --- a/tests/test_native_columnar_parallel.py +++ b/tests/test_native_columnar_parallel.py @@ -6,6 +6,9 @@ JVM wheel. Needs the native library, so conftest.py collects this file on the native backend only. Each test loads the same data through the row path (the private reference: ``insert_many(parallel=True)`` with dict rows) and through the columns, compares the stored records value by value and type by type, and spies on the entry points so a silent fall back cannot pass. + +The types compared are the Python types read back. insert_many stores a whole number that fits an int as an Integer and +insert_columns as a Long (tests/test_insert_many_integer_types.py), and both read back as int. """ import numpy as np From 2ad03760d48d428e1a3f4c1e071ffea7a1cfc821 Mon Sep 17 00:00:00 2001 From: Taewoon Kim Date: Fri, 27 Nov 2026 06:21:31 +0900 Subject: [PATCH 5/5] Tests: the replacements of insert_parallel pass its new flag through --- tests/test_native_columnar_parallel_review_fixes.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/tests/test_native_columnar_parallel_review_fixes.py b/tests/test_native_columnar_parallel_review_fixes.py index 70f17bc3..4afcdf36 100644 --- a/tests/test_native_columnar_parallel_review_fixes.py +++ b/tests/test_native_columnar_parallel_review_fixes.py @@ -51,8 +51,8 @@ def failures(database, token): self.read.append(token) return real_read(database, token) - def rows(database, type_name, chunk): - fid = real_rows(database, type_name, chunk) + def rows(database, type_name, chunk, *flags): + fid = real_rows(database, type_name, chunk, *flags) self.made.append(fid["fid"]) return fid @@ -142,11 +142,11 @@ def test_an_interrupt_between_the_chunks_of_the_row_path_waits_and_reads_the_tok real_rows = extras.insert_parallel seen = [] - def second_chunk_interrupted(database, type_name, chunk): + def second_chunk_interrupted(database, type_name, chunk, *flags): if seen: raise KeyboardInterrupt seen.append(1) - return real_rows(database, type_name, chunk) + return real_rows(database, type_name, chunk, *flags) monkeypatch.setattr(extras, "insert_parallel", second_chunk_interrupted) rows = [{"id": i, "txt": "t"} for i in range(25_000)]