Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/modules/ROOT/pages/how-to/bulk-loads.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
6 changes: 5 additions & 1 deletion docs/modules/ROOT/pages/upgrading.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -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].

Expand Down Expand Up @@ -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:
Expand Down
6 changes: 4 additions & 2 deletions native/src/main/java/org/humemai/nativelib/ArcadeNative.java
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand Down
106 changes: 98 additions & 8 deletions native/src/main/java/org/humemai/nativelib/BulkOps.java
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,8 @@ static long handColumns(final Database db, final String type, final Map<String,
* LocalDateTime), D (int32 days since the epoch, a LocalDate), n (a decimal as text in the string layout, a BigDecimal) and x (bytes in
* the string layout, a byte[]), so a column of these is stored as the row path stores it. spec: per column six longs, [data address, data bytes, aux address, aux bytes, null
* bitmap address, null bitmap bytes]; the bitmap is Arrow's (bit i of byte i/8, least significant first; 1 = present), an address of 0
* means no nulls. The memory belongs to the caller for the duration of the call; nothing is kept. Every length is checked here before
* means no nulls. A header with "narrow":true (insert_many) stores a whole number of a q column that fits an int as an Integer.
* The memory belongs to the caller for the duration of the call; nothing is kept. Every length is checked here before
* the first document is built, so a wrong table is an exception and nothing is written. Same transaction contract as
* DocumentBatcher.insertColumns: batch commits and the rollback on failure apply only to a transaction opened here.
* onError null: the synchronous mode above. Not null (header "parallel":true): every record goes to db.async().createRecord with that
Expand All @@ -118,6 +119,7 @@ static long handColumns(final Database db, final String type, final Map<String,
private static long insertColumns(final Database db, final String type, final Map<String, Object> 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);
Expand All @@ -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
Expand All @@ -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;
Expand Down Expand Up @@ -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<Object> list = (List<Object>) 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<Object, Object> entry : ((Map<Object, Object>) 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;
}

/**
Expand Down Expand Up @@ -417,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<String, Object> e : row.entrySet())
doc.set(e.getKey(), e.getValue());
doc.set(e.getKey(), narrow ? narrowedDeep(e.getValue()) : e.getValue());
doc.save();
count[0]++;
});
Expand Down
7 changes: 5 additions & 2 deletions native/src/main/java/org/humemai/nativelib/NativeExtras.java
Original file line number Diff line number Diff line change
Expand Up @@ -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<String, Object> e : ((Map<String, Object>) row).entrySet())
doc.set(e.getKey(), e.getValue());
// "narrow" (insert_many): whole numbers are typed as insert_many without parallel types them (BulkOps.narrowed)
final Map<String, Object> values = (Map<String, Object>) row;
final boolean narrow = Boolean.TRUE.equals(a.get("narrow")) && BulkOps.rowCarriedByText(values);
for (final Map.Entry<String, Object> e : values.entrySet())
doc.set(e.getKey(), narrow ? BulkOps.narrowedDeep(e.getValue()) : e.getValue());
ex.createRecord(doc, null, onError);
}
} catch (final Throwable t) {
Expand Down
12 changes: 7 additions & 5 deletions src/arcadedb/_native/bulk.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -96,7 +97,8 @@ 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}'"
_send(db, type_name, cols, rows, 0, prefix, narrow=narrow)
return True


Expand Down
7 changes: 5 additions & 2 deletions src/arcadedb/_native/columnar.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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)


Expand Down
Loading
Loading