Skip to content

Commit c0f9647

Browse files
authored
fix(#10553, #10522, #10426): a held database is UNAVAILABLE on every wire protocol, one temporal encoder for the Python JSON writer, a failed snapshot restore keeps schema.json (#10564)
* fix(#10553, #10522, #10426): a held database is UNAVAILABLE on every wire protocol, the Python JSON writer has no temporal encoder of its own, a failed snapshot restore keeps schema.json in the backup #10553: ErrorCategory.UNAVAILABLE (DatabaseNotAvailableException without its not-found subtype) decided once in the engine. gRPC UNAVAILABLE, Postgres 57P03, Bolt DatabaseUnavailable, Redis LOADING and MongoDB 365 TemporarilyUnavailable now read it from the category instead of a private predicate each. Redis also took a held database's prefix for part of a plain key and acknowledged the write into the connection's own bucket; ArcadeDBServer.isDatabaseHeld() lets it recognise the name. #10522: RowBatcher drops its own LocalDate/Calendar encoder and writes through the engine's JSONObject like every other row shape, so a date past the range of a long of milliseconds is ISO text instead of failing the whole batch. The days form of Result.to_json() for a record row is the engine's round-trip form and is documented and pinned, not copied. #10426: SnapshotInstaller.restoreBackup moved entries back in directory-listing order, which APFS sorts and ext4/overlayfs/tmpfs do not, so schema.json left the backup before a failing move on Linux only. The schema files now go back last. * test(#10522): a bridge that follows an engine which cannot write a far date raises ArcadeDBError, not a bare Java exception The Python jobs of CI bundle the engine of the published snapshot image, whose JSONObject still throws on a date past year 292 million; the bridge follows it, and the bindings raise a Java failure of a read as ArcadeDBError. Verified locally with that image's engine jar. * review(#10553): the manual recovery text names the installer's own entries by exact name, a held Redis default database is refused, Bolt's parsing catches answer through the category SnapshotInstaller: the refusal no longer says to keep every entry starting with .snapshot (a bucket may legally be named so, #9446); it lists SNAPSHOT_MACHINERY_FILES and SNAPSHOT_MACHINERY_DIRS by name. RedisNetworkExecutor: a held REDIS_DEFAULT_DATABASE is recorded as the connection's database so an unprefixed write is answered LOADING and not kept in the connection-local bucket. BoltNetworkExecutor: both CommandParsingException catches of RUN answer through classifyExecutionError, which keeps a genuine syntax error's title and lets a held database wrapped by that exception say what it is. * review(#10553): a close command marks the database before it leaves the registry, so a lock-free reader that finds it gone finds it held removeDatabase deregistered first and marked second, leaving an instant where isDatabaseHeld() and existsDatabase() were both false for a database a close command was closing. The mark now goes up first; callers read existsDatabase() then isDatabaseHeld(), which the Javadoc says. * review(#10553): the manual recovery steps are a numbered list, the Redis call site says why existsDatabase comes before isDatabaseHeld * fix(#10426): the installer's entry names for the recovery text are computed, not a static String that the machinery guards read as a file SnapshotManagerTest and Issue9446SnapshotPrefixedBucketTest treat every static String of SnapshotInstaller whose value starts with .snapshot as one more entry the install writes into a database directory; the constant added for the recovery text matched. It is a method now. * review(#10426): the refusal of a retained backup sends the operator to the restart-time recovery and deletes nothing by hand A live entry absent from .snapshot-backup can be an original the failed install never moved into it (failure during BACKING_UP) or an entry already moved back by the failed restore; a name does not tell which, so no step of the message deletes one. The unused helper that listed the installer's entry names is gone.
1 parent ee04bd2 commit c0f9647

26 files changed

Lines changed: 1019 additions & 110 deletions

File tree

‎bindings/python/src/arcadedb_embedded/results.py‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -529,6 +529,18 @@ def to_json_list(self, batch_size: int = 10_000) -> List[Dict[str, Any]]:
529529
floats. Use ``to_list()`` when you want ``date``, ``datetime`` and
530530
``Decimal`` values: it costs about the same.
531531
532+
The encoding is one rule for every row, at the top level and inside a
533+
list or a map: a DATE is the epoch milliseconds of its UTC midnight (not
534+
a count of days) whatever the JVM time zone, the same number
535+
``to_columns()`` carries as ``datetime64[ms]``. A date too far from 1970
536+
for a long of milliseconds (past about year 292 million) arrives as its
537+
ISO-8601 text instead of failing the batch.
538+
539+
This is NOT the form of ``Result.to_json()`` for a record row (``SELECT
540+
FROM T``), which is the engine's round-trip JSON of the record: there a
541+
DATE column at the top level is epoch DAYS, with the ``@rid``, ``@type``
542+
and ``@cat`` metadata. Do not mix the two when decoding a DATE.
543+
532544
Args:
533545
batch_size: Rows serialized per Java crossing (default 10000)
534546
@@ -1303,6 +1315,18 @@ def to_json(self) -> str:
13031315
"""
13041316
Convert result to JSON string.
13051317
1318+
This is the engine's own JSON of the row. For a record row (``SELECT
1319+
FROM T``) it is the record's round-trip form, which ``fromJSON`` reads
1320+
back: it carries the ``@rid``, ``@type`` and ``@cat`` metadata and writes
1321+
a top-level DATE as epoch DAYS (a DATETIME as epoch milliseconds, or as
1322+
text when its column keeps microseconds or nanoseconds). A DATE inside a
1323+
list or a map, and a DATE in a projection row (``SELECT a, b FROM T``),
1324+
is written as the epoch milliseconds of its UTC midnight, the form
1325+
``ResultSet.to_json_list()`` uses everywhere; a DATETIME in a projection
1326+
row is written as text in the schema's date-time format. The engine's
1327+
JSON is not one encoding across row shapes, which is why
1328+
``to_json_list()`` does not delegate to it.
1329+
13061330
Returns:
13071331
JSON string representation
13081332

‎bindings/python/src/java/com/arcadedb/python/ColumnBatcher.java‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,10 @@ private ColumnBatcher() {
4242
}
4343

4444
/** Wall-clock-consistent epoch millis: naive temporals are read as UTC so
45-
* numpy's (naive) datetime64 shows the same wall-clock the record carries. */
45+
* numpy's (naive) datetime64 shows the same wall-clock the record carries.
46+
* A DATE is its UTC midnight in milliseconds, not a count of days: the column is a datetime64[ms], and it is the
47+
* number RowBatcher gets from the engine's JSONObject for the same value (#10522, test_temporal_writers_agree.py).
48+
* It is not a JSON writer, so there is nothing for it to disagree with in Result.toJSON(). */
4649
private static long toEpochMillis(final Object v) {
4750
if (v instanceof Date d)
4851
return d.getTime();

‎bindings/python/src/java/com/arcadedb/python/RowBatcher.java‎

Lines changed: 18 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,16 @@
1212
* which since 26.7.2 (#4967) serializes primitive arrays like float[] as
1313
* real JSON arrays natively.
1414
*
15+
* This class has NO temporal encoding of its own (#10522): every date and
16+
* date-time is written by JSONObject.put, the writer the engine uses for the
17+
* rows of a projection and for the members of a list or a map of any row, and
18+
* ColumnBatcher's epoch milliseconds are the same numbers. A DATE is the epoch
19+
* milliseconds of its UTC midnight, never a count of days, whatever the JVM
20+
* time zone. The one place the engine writes days is the top level of a
21+
* record's own toJSON() (Result.to_json() of a SELECT FROM T row), which is
22+
* the form fromJSON() reads back for a DATE column; to_json_list() is not that
23+
* round trip, and test_temporal_writers_agree.py pins both.
24+
*
1525
* Compiled into arcadedb-python-bridge.jar during the wheel build
1626
* (scripts/Dockerfile.build and scripts/build-native.sh) and consumed by
1727
* ResultSet.to_json_list() in the Python bindings. Values carry JSON-native
@@ -24,14 +34,6 @@
2434
import com.arcadedb.query.sql.executor.ResultSet;
2535
import com.arcadedb.serializer.json.JSONObject;
2636

27-
import java.time.LocalDate;
28-
import java.time.ZoneOffset;
29-
import java.util.ArrayList;
30-
import java.util.Calendar;
31-
import java.util.LinkedHashMap;
32-
import java.util.List;
33-
import java.util.Map;
34-
3537
public final class RowBatcher {
3638

3739
private RowBatcher() {
@@ -79,49 +81,14 @@ static void closeDrained(final ResultSet rs) {
7981

8082
private static void appendRow(final StringBuilder sb, final Result row) {
8183
final JSONObject obj = new JSONObject();
82-
for (final String property : row.getPropertyNames())
83-
obj.put(property, utcDates(row.getProperty(property)));
84-
sb.append(obj);
85-
}
86-
87-
/**
88-
* JSONObject.put writes a LocalDate as the epoch milliseconds of midnight in the JVM's default time zone, while
89-
* Result.toJSON() and a DATETIME (a UTC wall clock) are written in UTC, so the same row read twice gave two integers
90-
* and decoded to the previous day east of UTC. A DATE is written as midnight UTC here, at the top level and inside a
91-
* list or map. A collection without a LocalDate is returned as it is.
92-
* <p>
93-
* A java.util.Calendar (arcadedb.dateTimeImplementation / dateImplementation) is written as its epoch milliseconds, as
94-
* a java.util.Date is. The engine's JSONObject wrote it as its toString() before #9630, and this bridge runs against
95-
* whatever engine the wheel bundles, so it does not rely on that fix.
96-
*/
97-
private static Object utcDates(final Object value) {
98-
if (value instanceof LocalDate date)
99-
return date.atStartOfDay(ZoneOffset.UTC).toInstant().toEpochMilli();
100-
if (value instanceof Calendar calendar)
101-
return calendar.getTimeInMillis();
102-
if (value instanceof List<?> list) {
103-
List<Object> copy = null;
104-
for (int i = 0; i < list.size(); i++) {
105-
final Object element = list.get(i);
106-
final Object converted = utcDates(element);
107-
if (converted != element && copy == null)
108-
copy = new ArrayList<>(list);
109-
if (copy != null)
110-
copy.set(i, converted);
111-
}
112-
return copy != null ? copy : value;
84+
for (final String property : row.getPropertyNames()) {
85+
// No conversion of our own: JSONObject.put anchors a LocalDate at UTC midnight whatever the JVM zone (#9037), writes a
86+
// java.util.Calendar as its epoch milliseconds like a Date (#9630), and writes a date past the range of a long of
87+
// milliseconds as its ISO text (#10483), where the encoder this replaced threw and failed the whole batch. The members
88+
// of a list or a map go the same way
89+
final Object value = row.getProperty(property);
90+
obj.put(property, value);
11391
}
114-
if (value instanceof Map<?, ?> map) {
115-
Map<Object, Object> copy = null;
116-
for (final Map.Entry<?, ?> entry : map.entrySet()) {
117-
final Object converted = utcDates(entry.getValue());
118-
if (converted != entry.getValue() && copy == null)
119-
copy = new LinkedHashMap<>(map);
120-
if (copy != null)
121-
copy.put(entry.getKey(), converted);
122-
}
123-
return copy != null ? copy : value;
124-
}
125-
return value;
92+
sb.append(obj);
12693
}
12794
}

‎bindings/python/tests/test_bridge_fixes.py‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,10 @@ def test_to_json_list_writes_a_date_as_midnight_utc_in_any_jvm_zone(tmp_path, zo
8484
it writes this undeclared LocalDate as days since the epoch, as it writes a
8585
declared DATE; before that it wrote midnight UTC milliseconds. The engine is
8686
asked which of the two it does (a version number cannot tell: 26.11.1
87-
snapshots from before #10253 exist), and the test holds it to that one."""
87+
snapshots from before #10253 exist), and the test holds it to that one.
88+
That the bridge writes milliseconds where the record's own JSON writes days
89+
is a decision and not a drift (#10522): test_temporal_writers_agree.py pins
90+
it, and pins that every bridge writer agrees with the engine's generic one."""
8891
proc = subprocess.run( # nosec B603 - fixed argv, no shell, test-owned
8992
[sys.executable, "-c", _DATE_SCRIPT, str(tmp_path / "db"), zone],
9093
capture_output=True,
Lines changed: 172 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,172 @@
1+
"""The bridge's bulk writers have one temporal encoding, and it is the engine's (#10522).
2+
3+
``to_json_list()`` (``RowBatcher``) and ``to_columns()`` (``ColumnBatcher``) used to carry an encoder of their
4+
own for a date, written when the engine had no type for a ``LocalDate``. The engine has since fixed what that
5+
encoder worked around (a ``LocalDate`` is UTC midnight whatever the JVM zone, a ``Calendar`` is its milliseconds,
6+
a date past the range of a long is text), so the private copy only differed from the engine's generic JSON writer
7+
in the one place it was worse: a date past year 292 million threw and failed the whole batch.
8+
9+
What these tests hold is the rule the issue asks for, in a form that survives the next engine-side type mapping:
10+
for every temporal type the JSON writer, the columnar writer and ``JSONObject.put`` write the same number, at the
11+
top level and inside a list or a map, in a record row and in a projection row. The one number that differs, a
12+
DATE column at the top level of ``Result.to_json()`` of a record row (days), is the engine's round-trip form of
13+
the record and is pinned separately, so its difference is a decision written down and not a drift.
14+
15+
Author: Luca Garulli ([email protected])
16+
"""
17+
18+
import datetime as dt
19+
import json
20+
21+
import arcadedb_embedded as arcadedb # noqa: F401 (starts the JVM through the fixtures)
22+
import jpype
23+
import numpy as np
24+
import pytest
25+
from arcadedb_embedded import results
26+
from arcadedb_embedded.exceptions import ArcadeDBError
27+
28+
MIDNIGHT_UTC_2024_01_02 = 1704153600000
29+
DAY_MS = 86_400_000
30+
31+
32+
def _in_memory(rows):
33+
"""A result set over rows built in Java, for values SQL cannot produce."""
34+
internal = jpype.JClass("com.arcadedb.query.sql.executor.InternalResultSet")()
35+
result_internal = jpype.JClass("com.arcadedb.query.sql.executor.ResultInternal")
36+
for row in rows:
37+
java_row = result_internal()
38+
for key, value in row.items():
39+
java_row.setProperty(key, value)
40+
internal.add(java_row)
41+
return internal
42+
43+
44+
def _java_temporals():
45+
"""One value of every temporal class a row can hold, with sub-millisecond digits and a pre-epoch instant."""
46+
java = jpype.JClass
47+
instant = java("java.time.Instant").parse("2024-01-02T03:04:05.123456789Z")
48+
calendar = java("java.util.Calendar").getInstance(
49+
java("java.util.TimeZone").getTimeZone("UTC")
50+
)
51+
calendar.setTimeInMillis(jpype.JLong(1704164645123))
52+
return {
53+
"local_date": java("java.time.LocalDate").of(2024, 1, 2),
54+
"pre_epoch_date": java("java.time.LocalDate").of(1969, 12, 31),
55+
"local_date_time": java("java.time.LocalDateTime").of(
56+
2024, 1, 2, 3, 4, 5, 123_456_789
57+
),
58+
"pre_epoch_date_time": java("java.time.LocalDateTime").of(
59+
1969, 12, 31, 23, 59, 59, 999_500_000
60+
),
61+
"instant": instant,
62+
"zoned": java("java.time.ZonedDateTime").ofInstant(
63+
instant, java("java.time.ZoneId").of("Asia/Seoul")
64+
),
65+
"offset": java("java.time.OffsetDateTime").parse("2024-01-02T03:04:05.5+09:00"),
66+
"util_date": java("java.util.Date")(jpype.JLong(1704164645123)),
67+
"calendar": calendar,
68+
}
69+
70+
71+
def _engine_json(name, value):
72+
"""What the engine's generic JSON writer makes of ``value``: the parsed text, or the exception's class name."""
73+
json_object = jpype.JClass("com.arcadedb.serializer.json.JSONObject")()
74+
try:
75+
json_object.put(name, value)
76+
except jpype.JException as exc:
77+
return {"raises": str(exc.getClass().getName())}
78+
return json.loads(str(json_object.toString()))
79+
80+
81+
def test_the_json_and_columnar_writers_write_the_same_number_for_every_temporal(
82+
temp_db,
83+
):
84+
values = _java_temporals()
85+
86+
as_json = results.ResultSet(_in_memory([values]), temp_db).to_json_list()[0]
87+
columns = results.ResultSet(_in_memory([values]), temp_db).to_columns()
88+
89+
assert set(columns) == set(values)
90+
for name in values:
91+
column = columns[name]
92+
assert column.dtype == np.dtype("datetime64[ms]"), name
93+
assert int(column[0].astype("int64")) == as_json[name], name
94+
95+
96+
def test_the_json_writer_is_the_engines_generic_writer_for_every_temporal(temp_db):
97+
"""No encoder of its own: if the engine's JSONObject changes how it writes a type, this fails and a decision is made."""
98+
values = _java_temporals()
99+
# a date past the range of a long of milliseconds: text for an engine that has #10483, a failure for one that has not,
100+
# and the bridge follows either way
101+
values["far_date"] = jpype.JClass("java.time.LocalDate").of(999_999_999, 12, 31)
102+
dates = jpype.JClass("java.util.ArrayList")()
103+
dates.add(values["local_date"])
104+
dates.add(values["pre_epoch_date"])
105+
values["dates"] = dates
106+
members = jpype.JClass("java.util.LinkedHashMap")()
107+
members.put("on", values["local_date"])
108+
values["meta"] = members
109+
110+
for name, value in values.items():
111+
expected = _engine_json(name, value)
112+
if "raises" in expected:
113+
# the bridge follows the engine it bundles, and the bindings raise a Java failure of a read as ArcadeDBError
114+
with pytest.raises(ArcadeDBError):
115+
results.ResultSet(_in_memory([{name: value}]), temp_db).to_json_list()
116+
else:
117+
row = results.ResultSet(_in_memory([{name: value}]), temp_db).to_json_list()
118+
assert row == [expected], name
119+
120+
121+
def test_a_date_is_one_number_in_a_record_row_a_projection_row_a_list_and_a_map(
122+
temp_db,
123+
):
124+
temp_db.command("sql", "CREATE DOCUMENT TYPE Event")
125+
temp_db.command("sql", "CREATE PROPERTY Event.day DATE")
126+
with temp_db.transaction():
127+
temp_db.command(
128+
"sql",
129+
"INSERT INTO Event SET day = :day, days = :days, meta = :meta",
130+
{
131+
"day": dt.date(2024, 1, 2),
132+
"days": [dt.date(2024, 1, 2)],
133+
"meta": {"on": dt.date(2024, 1, 2)},
134+
},
135+
)
136+
137+
record_row = temp_db.query("sql", "SELECT FROM Event").to_json_list()[0]
138+
projection_row = temp_db.query(
139+
"sql", "SELECT day, days, meta FROM Event"
140+
).to_json_list()[0]
141+
142+
expected = {
143+
"day": MIDNIGHT_UTC_2024_01_02,
144+
"days": [MIDNIGHT_UTC_2024_01_02],
145+
"meta": {"on": MIDNIGHT_UTC_2024_01_02},
146+
}
147+
assert {key: record_row[key] for key in expected} == expected
148+
assert projection_row == expected
149+
150+
151+
def test_result_to_json_writes_the_top_level_date_of_a_record_row_as_days(temp_db):
152+
"""The one place the engine writes days: the round-trip JSON of the record, pinned so the difference is a decision.
153+
154+
A DATE column read back by ``fromJSON`` is a count of days, which is why ``Result.to_json()`` of a record row
155+
writes it so. ``to_json_list()`` is a read-only bulk transport and writes milliseconds everywhere, so a caller
156+
decodes every temporal the same way; the two differ by exactly the milliseconds in a day, and by nothing else.
157+
"""
158+
temp_db.command("sql", "CREATE DOCUMENT TYPE Event")
159+
temp_db.command("sql", "CREATE PROPERTY Event.day DATE")
160+
with temp_db.transaction():
161+
temp_db.command(
162+
"sql",
163+
"INSERT INTO Event SET day = :day",
164+
{"day": dt.date(2024, 1, 2)},
165+
)
166+
167+
single = json.loads(temp_db.query("sql", "SELECT FROM Event").first().to_json())
168+
batch = temp_db.query("sql", "SELECT FROM Event").to_json_list()[0]
169+
170+
assert single["day"] == MIDNIGHT_UTC_2024_01_02 // DAY_MS
171+
assert batch["day"] == single["day"] * DAY_MS
172+
assert "@rid" in single and "@rid" not in batch

‎bolt/src/main/java/com/arcadedb/bolt/BoltNetworkExecutor.java‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -838,7 +838,10 @@ private void handleRun(final RunMessage message) throws IOException {
838838
applySystemQueryTail(query, params, stream);
839839
} catch (final CommandParsingException e) {
840840
stream.close(this, "RUN failure");
841-
sendExecutionFailure(classifyParsingError(e), clientMessage(e.getMessage() != null ? e.getMessage() : "Query parsing error", e), e);
841+
// Through the category, which keeps a genuine parsing failure's own title (classifyParsingError) and lets a failure that
842+
// outranks parsing, wrapped by this exception, say what it is: a held database is not a syntax error (issue #10553)
843+
sendExecutionFailure(classifyExecutionError(e, BoltErrorCodes.DATABASE_ERROR),
844+
clientMessage(e.getMessage() != null ? e.getMessage() : "Query parsing error", e), e);
842845
state = State.FAILED;
843846
return;
844847
} catch (final Exception e) {
@@ -942,7 +945,8 @@ private void handleRun(final RunMessage message) throws IOException {
942945
} catch (final CommandParsingException e) {
943946
stream.close(this, "RUN failure");
944947
final String parseMsg = e.getMessage() != null ? e.getMessage() : "Query parsing error";
945-
sendExecutionFailure(classifyParsingError(e), clientMessage(parseMsg, e), e);
948+
// Through the category, as the system-query catch does (issue #10553)
949+
sendExecutionFailure(classifyExecutionError(e, BoltErrorCodes.DATABASE_ERROR), clientMessage(parseMsg, e), e);
946950
state = State.FAILED;
947951
} catch (final Exception e) {
948952
// MVCC conflicts (NeedRetryException) are expected under contention and auto-retried by the driver,
@@ -2021,6 +2025,9 @@ static String classifyExecutionError(final Throwable error, final String default
20212025
case TIMEOUT -> BoltErrorCodes.TRANSACTION_TIMED_OUT_ERROR;
20222026
// Stopped on request (issue #9689): the one Transaction.* title meaning "killed on purpose", which drivers never retry
20232027
case TERMINATED -> BoltErrorCodes.TRANSACTION_TERMINATED_ERROR;
2028+
// A database the server has and cannot serve now (issue #10553), reached here when it is lost under a statement rather than at
2029+
// the selection of the database (classifyDatabaseSelectionError): the same title, so the driver reads one thing either way
2030+
case UNAVAILABLE -> BoltErrorCodes.DATABASE_UNAVAILABLE_ERROR;
20242031
case SERVER -> defaultCode;
20252032
};
20262033
}

0 commit comments

Comments
 (0)