From e517cdb73039d4c64679f2225180c947444986b1 Mon Sep 17 00:00:00 2001 From: Taewoon Kim Date: Fri, 27 Nov 2026 05:25:24 +0900 Subject: [PATCH] Native Result.to_json(): write text outside ASCII as it is, as the JVM build does The JVM build's to_json() is the engine's writer: a character outside ASCII is written as it is. The native build used json.dumps with its default ensure_ascii, so the same row was a different, longer text. It now writes with ensure_ascii=False and escapes U+2028, U+2029 and lone surrogates afterwards, so the text matches the JVM build and always has a UTF-8 form. A golden test with two, three and four byte characters runs on both wheels. The upgrade page states the changed text. --- .../pages/how-to/databases-and-queries.adoc | 2 +- docs/modules/ROOT/pages/upgrading.adoc | 6 +++- src/arcadedb/_native/database.py | 13 +++++++- tests/test_cross_wheel_golden.py | 30 +++++++++++++++++++ 4 files changed, 48 insertions(+), 3 deletions(-) diff --git a/docs/modules/ROOT/pages/how-to/databases-and-queries.adoc b/docs/modules/ROOT/pages/how-to/databases-and-queries.adoc index 26fd833..8b1e578 100644 --- a/docs/modules/ROOT/pages/how-to/databases-and-queries.adoc +++ b/docs/modules/ROOT/pages/how-to/databases-and-queries.adoc @@ -272,7 +272,7 @@ A query vector for `vectorNeighbors` can be a numpy array or a list. This sectio * `to_list()` materialises the whole result as a list of dicts, one Python dict per row. Use it for a small result, or when you need the whole result in memory; iterate when you stop early. For a large result, see <>. * `to_json_list(batch_size=10_000)` returns the rows as a list of JSON-native dicts, the same on both builds. A `DATE` or `DATETIME` is a number of epoch milliseconds, a record id is its text, and every `DECIMAL` is a `float` whatever its scale, so `Decimal("3")` is `3.0` and one column has one Python type. A `float` keeps about 17 significant digits, so a `DECIMAL` with more digits is rounded: `to_list()` returns the `Decimal` with every digit. * `iter_json_batches(batch_size=10_000)` yields the rows as lists of JSON-native dicts, `batch_size` rows per list (the last may be shorter), with the same values as `to_json_list()`. On the native build `batch_size` bounds memory: the result set holds one reply of the cursor (2048 rows) and one batch at a time, and reads the next reply only when the next batch is asked for, so a large result is never held whole. On the JVM build a batch is serialised on the Java side one at a time. `to_list()`, `to_json_list()`, `to_dataframe()`, `to_columns()`, `to_arrow()` and `to_polars()` still hold the whole result, because they return it whole. -* `Result.to_json()` returns the text of one row, and the values in it are the same on both builds, but the text is not always. A `FLOAT` or a `float32` array is written as the shortest `float32` text on `arcadedb-jvm` (`0.1`) and as the exact `float64` that the `float32` widens to on `arcadedb` (`0.10000000149011612`). Both read back as the same `float32`. Parse the text with `json.loads` and compare the numbers, and do not hash, diff or measure the text itself across the two builds. `to_json_list()` has no such difference: both builds return the exact widening. +* `Result.to_json()` returns the text of one row, and the values in it are the same on both builds, but the text is not always. A `FLOAT` or a `float32` array is written as the shortest `float32` text on `arcadedb-jvm` (`0.1`) and as the exact `float64` that the `float32` widens to on `arcadedb` (`0.10000000149011612`). Both read back as the same `float32`. Text in a string is written the same on both: a character outside ASCII as it is, and a `\u` escape only for control characters, U+2028 and U+2029. Parse the text with `json.loads` and compare the numbers, and do not hash, diff or measure the text itself across the two builds. `to_json_list()` has no such difference: both builds return the exact widening. + One laptop study on the native build, 1,000,000 rows read with `batch_size=10_000`, 10 clean pairs of this change against the previous behaviour; each figure is the ratio of the new value to the old one, so below 1 is lower. Peak RSS: 0.286 (95% interval 0.284 to 0.289). Time to the first batch: 0.010 (95% interval 0.009 to 0.010). Wall time of the whole read: 0.958 (95% interval 0.952 to 0.966). This is one machine and one result shape, not a speed promise. diff --git a/docs/modules/ROOT/pages/upgrading.adoc b/docs/modules/ROOT/pages/upgrading.adoc index 689009a..1bf4420 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. Pinned by tests/test_auto_transaction_default.py, tests/test_error_codes_table.py, tests/test_error_codes_parity.py and tests/test_lazy_import.py. +// 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. 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]. @@ -37,6 +37,10 @@ See xref:how-to/errors.adoc[Errors: codes, hints and classes]. `import arcadedb` no longer imports NumPy itself (`{jvm-pkg-name}` can still import it at that point through JPype). A NumPy that is installed but cannot be imported now raises at the first call that needs it. Before, the packages acted as if NumPy were not installed. +=== `{native-pkg-name}` writes text outside ASCII as it is in `Result.to_json()` + +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. + === Engine 26.12.1 The engine that the 26.12.1 packages carry changes some behaviour that the other pages describe: diff --git a/src/arcadedb/_native/database.py b/src/arcadedb/_native/database.py index 950e410..5957301 100644 --- a/src/arcadedb/_native/database.py +++ b/src/arcadedb/_native/database.py @@ -40,6 +40,10 @@ " call only." ) _RID_RE = re.compile(r"#?-?\d+:-?\d+") +# Result.to_json() writes text as the JVM build does (the engine's writer): a character outside ASCII as it is, and a \u escape only +# for a control character and for U+2028 and U+2029. json.dumps(ensure_ascii=False) leaves those two as they are, and a lone +# surrogate too, which has no UTF-8 form, so these three kinds are escaped after it. +_JSON_TEXT_ESCAPED = re.compile(r"[\u2028\u2029\ud800-\udfff]") _FIRST_BATCH = 256 _EPOCH_DAY_ORDINAL = date(1970, 1, 1).toordinal() _NEXT_BATCH = 2048 @@ -48,6 +52,10 @@ _KIND = {"v": "v", "e": "e", "d": "d"} +def _json_u_escape(match) -> str: + return "\\u%04x" % ord(match.group()) + + def _error(prefix: str, reply: dict) -> ArcadeDBError: """The ArcadeDBError for a failed reply, worded like the JPype path (``prefix: java.class: message``).""" chain = reply.get("chain") or [] @@ -189,7 +197,10 @@ def to_json(self) -> str: out["@cat"] = kind out["@type"] = type_name out["@rid"] = rid - return json.dumps(out, default=str, separators=(",", ":")) + text = json.dumps(out, default=str, separators=(",", ":"), ensure_ascii=False) + if text.isascii(): + return text + return _JSON_TEXT_ESCAPED.sub(_json_u_escape, text) def __repr__(self) -> str: names = list(self._props) diff --git a/tests/test_cross_wheel_golden.py b/tests/test_cross_wheel_golden.py index 29bb38b..f72f913 100644 --- a/tests/test_cross_wheel_golden.py +++ b/tests/test_cross_wheel_golden.py @@ -296,6 +296,36 @@ def test_to_json_text_of_a_projection_row_golden(golden): assert texts == GOLDEN_JSON_TEXT +# a STRING outside ASCII (two, three and four bytes of UTF-8), the characters an HTML-safe writer would escape, and the characters +# JSON has to escape, as a value, inside a LIST and as a MAP key and value (#454) +TEXT = "é € \U0001f600 \u2028\u2029 <&='\" \\ \n\t\x01\x7f" +GOLDEN_TEXT_ROW = ( + '{"s":"é € \U0001f600 \\u2028\\u2029 <&=\'\\" \\\\ \\n\\t\\u0001\x7f",' + '"l":["é","\U0001f600"],"m":{"clé":"ü"}}' +) + + +def test_to_json_text_outside_ascii_golden(temp_db): + """``Result.to_json()`` writes text outside ASCII as it is on both builds, and escapes the same few characters. + + The native build used to write every character outside ASCII as a ``\\u`` escape (#454). + """ + temp_db.command("sql", "CREATE DOCUMENT TYPE Txt") + for name, type_name in [("s", "STRING"), ("l", "LIST"), ("m", "MAP")]: + temp_db.command("sql", f"CREATE PROPERTY Txt.{name} {type_name}") + temp_db.insert_many( + "Txt", [{"s": TEXT, "l": ["é", "\U0001f600"], "m": {"clé": "ü"}}] + ) + + row = temp_db.query("sql", "SELECT s, l, m FROM Txt").first() + assert row.to_json() == GOLDEN_TEXT_ROW + assert json.loads(row.to_json())["s"] == TEXT + + record = temp_db.query("sql", "SELECT FROM Txt").first().to_json() + assert '"é","\U0001f600"' in record + assert "\\u00e9" not in record + + def test_to_json_of_a_record_row_golden(golden): """``Result.to_json()`` of a record row reads back to the same values on both builds, the float32 values as float32.