Skip to content
This repository was archived by the owner on Nov 21, 2026. It is now read-only.
This repository was archived by the owner on Nov 21, 2026. It is now read-only.

append_samples(primitive=True) raises 'truth value of an array is ambiguous' for a NumPy tag or bool column, and silently pads a column that is shorter than the timestamps #124

Closed

Description

@tae898

Level: bindings. Two defects in the primitive=True path of AsyncExecutor.append_samples. First, a tag column given as a NumPy array of strings (for example pandas.Series(...).to_numpy()), or a field column given as a NumPy bool array, raises ValueError: The truth value of an array with more than one element is ambiguous; the default path (primitive=False) accepts the same arrays. Second, a column with fewer values than there are timestamps is padded without an error: a short tag list stores the tag '' for the missing row and a short field array stores NULL, where the default path rejects the whole append (through the executor's error callback, and no row is stored).

Repro

The script prints to stdout. The JVM's own log lines go to stderr and are discarded by the command below.

uv venv .venv
uv pip install --python .venv/bin/python arcadedb_embedded-26.10.1.dev0-cp312-cp312-manylinux_2_34_x86_64.whl numpy pandas
.venv/bin/python repro-19-append-samples-primitive-numpy-columns.py 2>/dev/null
"""append_samples(primitive=True) raises 'truth value of an array is ambiguous' for a NumPy tag or bool column, and pads short columns."""
import os
import tempfile

import numpy as np
import pandas as pd

import arcadedb_embedded as arcade
from arcadedb_embedded.jvm import start_jvm

start_jvm(heap_size="2g")
db = arcade.create_database(os.path.join(tempfile.mkdtemp(prefix="hb19-"), "db"))
ts = np.array([1000, 2000, 3000], dtype=np.int64)
vals = np.array([1.5, 2.5, 3.5])
hosts_list = ["a", "b", "c"]
cases = {
    "tags as list": (hosts_list, vals),
    "tags as np.array of str": (np.array(hosts_list), vals),
    "tags as pandas .to_numpy()": (pd.Series(hosts_list).to_numpy(), vals),
    "field as np bool array": (hosts_list, np.array([True, False, True])),
    "tag list one row short": (hosts_list[:2], vals),
    "field array one row short": (hosts_list, vals[:2]),
}
n = 0
print(f"{'case':<28} {'primitive=False':<44} primitive=True")
for label, (hosts, field) in cases.items():
    cells = []
    for primitive in (False, True):
        n += 1
        t = f"Metric{n}"
        db.command("sql", f"CREATE TIMESERIES TYPE {t} TIMESTAMP ts TAGS (host STRING) FIELDS (val DOUBLE) SHARDS 1")
        errors = []
        ex = db.async_executor()
        ex.on_error(lambda e: errors.append(type(e).__name__))
        try:
            ex.append_samples(t, ts, hosts, field, primitive=primitive)
            ex.wait_completion()
        except Exception as e:
            cells.append(f"raises {type(e).__name__}: {str(e)[:22]}...")
            continue
        rows = db.query("sql", f"SELECT host, val FROM {t} ORDER BY ts").to_list()
        cells.append(f"{[(r['host'], r['val']) for r in rows]}" + (f" on_error={errors}" if errors else ""))
    print(f"{label:<28} {cells[0]:<44} {cells[1]}")
db.close()

Output

Wheel arcadedb_embedded-26.10.1.dev0-cp312-cp312-manylinux_2_34_x86_64.whl with its bundled JRE (OpenJDK 25.0.4.1), JPype 1.7.1, and Python 3.12.13. The engine build the wheel reports through com.arcadedb.Constants is 26.10.1-SNAPSHOT (build 04bb03ebec07fce19101595d65ca1e3bdf516755), an ancestor of upstream cecb369df9. The repository is at f92ac1381c8335249a6fde644cbf04594f6d6391, and the installed Python sources are identical to bindings/python/src/arcadedb_embedded/ at that commit.

case                         primitive=False                              primitive=True
tags as list                 [('a', 1.5), ('b', 2.5), ('c', 3.5)]         [('a', 1.5), ('b', 2.5), ('c', 3.5)]
tags as np.array of str      [('a', 1.5), ('b', 2.5), ('c', 3.5)]         raises ValueError: The truth value of an ...
tags as pandas .to_numpy()   [('a', 1.5), ('b', 2.5), ('c', 3.5)]         raises ValueError: The truth value of an ...
field as np bool array       [('a', 1.0), ('b', 0.0), ('c', 1.0)]         raises ValueError: The truth value of an ...
tag list one row short       [] on_error=['com.arcadedb.exception.DatabaseOperationException'] [('a', 1.5), ('b', 2.5), ('', 3.5)]
field array one row short    [] on_error=['com.arcadedb.exception.DatabaseOperationException'] [('a', 1.5), ('b', 2.5), ('c', None)]

Cause

_append_samples_primitive chooses the column writer with elif values and all(isinstance(v, str) for v in values) and the same values and test for the float and int branches (async_executor.py L581-L593). For a NumPy array of dtype other than float, int, or uint (a <U string array, an object array, a bool array) the first test is bool(ndarray), which raises for more than one element.

The Java loops in TimeSeriesBatcher (TimeSeriesBatcher.java L41-L63) iterate the length of the column they were given, and nothing compares it with the number of timestamps before newBatch allocates the rows (async_executor.py L554), so rows that no setter reaches keep their defaults ('' for a tag, NULL for a field).

Expected

The primitive path accepts the same columns as the default path, and a column whose length differs from the timestamps is rejected with a ValueError before anything is appended.

Proposed fix

Test len(values) > 0 instead of the truthiness of values, and compare each column's length with len(timestamps) before newBatch. A run-time monkeypatch with these two edits makes the NumPy tag and bool columns work on the primitive path and turns the two short-column rows into ValueError. The default path's behaviour for a short column (the whole append lost, reported only through on_error) is a separate matter that I did not change.

--- a/bindings/python/src/arcadedb_embedded/async_executor.py
+++ b/bindings/python/src/arcadedb_embedded/async_executor.py
-            elif values and all(isinstance(v, str) for v in values):
+            elif len(values) > 0 and all(isinstance(v, str) for v in values):
@@ (the float and int branches likewise)
+        for column in column_values:
+            if len(column) != len(timestamps):
+                raise ValueError("every column needs one value per timestamp")
         batch = batcher.newBatch(self._owner._java_db, type_name, timestamps_java)

In the same function, a uint64 column or timestamp array with a value of 263 or more is converted with np.ascontiguousarray(values, dtype=np.int64) and wraps (a count of 263 is stored as -9223372036854775808 on both paths). I left it out of this report because the type's fields are LONG and the caller chose a uint64 array.

Related issues

ArcadeData#5474 (closed) is about boxing in appendSamples and added the primitive path; it does not cover these inputs.

In this repository's tracker no issue is about this. The searches for append_samples and async found only #99 (open), a flaky async SQL test.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions